Oluwafemi Akinyemi
Oluwafemi Akinyemi

Reputation: 119

Styling some parts of my React JSX rendered elements with CSS

I have an array of data that I'm mapping through in my small react project to render the contents of the data into the browser. But my problem is that I need to style some parts of these rendered contents and not all. Each of the CSS properties I'm applying is applicable to all the P tags. For Example, in the code below, The style will be applicable to Was, to Birthday in the second item, and so on...

Below is my CSS code.

import React from "react";
import "./styles.css";

export default function App() {
const data = [
  {
    details: 'Yesterday was his birthday'
  },
  {
    details: 'Today is my birthday'
  },
  {
    details: 'I cant\'t remember my birthday date'
  }
]

  return (
    <div className="App">
      <h1>I need Help</h1>
      <h2>Please How do i style some parts of my rendered details</h2>
      {
        data.map((detail)=>(
          <p>{detail.details}</p>
        ))
      }
    </div>
  );
}


Upvotes: 0

Views: 45

Answers (2)

Nick
Nick

Reputation: 16576

You can add a highlight prop to your array elements and split the sentence by that prop. Then, put the split word in its own span between the pieces.

export default function App() {
const data = [
  {
    details: 'Yesterday was his birthday',
    highlight: 'was'
  },
  {
    details: 'Today is my birthday',
    highlight: 'birthday'
  },
  {
    details: 'I cant\'t remember my birthday date',
    highlight: 'date'
  }
]

  return (
    <div className="App">
      <h1>I need Help</h1>
      <h2>Please How do i style some parts of my rendered details</h2>
      {data.map((datum) => {
        const pieces = datum.details.split(datum.highlight);
        return (
          <p key={datum.details}>
            {pieces[0]}
            <span style={{ backgroundColor: "#FF0" }}>{datum.highlight}</span>
            {pieces[1]}
          </p>
        );
      })}
    </div>
  );
}

Upvotes: 1

Krzysztof Podmokły
Krzysztof Podmokły

Reputation: 866

There are many ways to solve this problem. Then one suggested by @Nick is decent. You can also check my suggestion.

export default function App() {
const data = [
  {
    details: 'Yesterday was his birthday',
    css: true
  },
  {
    details: 'Today is my birthday',
    css: false
  },
  {
    details: 'I cant\'t remember my birthday date',
    css: false
  }
]

  return (
    <div className="App">
      <h1>I need Help</h1>
      <h2>Please How do i style some parts of my rendered details</h2>
      {
        data.map((detail)=>(
          <p className={detail.css ? 'my-custom-class' : ''}>{detail.details}</p>
        ))
      }
    </div>
  );
}

With this approach you will not have <p class="undefined">...</p>

Upvotes: 0

Related Questions