Using CSS to enhance the appearance of specific sections within my React JSX components

I'm currently working on a small React project where I'm mapping through an array of data to render its contents on the browser. However, I'm facing an issue regarding styling only certain parts of the rendered data and not all of them. The problem is that each CSS property I apply affects all the paragraph (P) tags uniformly. For instance, in the code snippet below, the styling should only be applied to "Was" in the first item, "Birthday" in the second item, and so on...

Here 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>
  );
}

Answer №1

To achieve the desired effect, you can introduce a 'mark' attribute to your array items and then divide the sentence based on this attribute. Subsequently, you can wrap the divided word in its individual span tag.

const ExampleComponent = () => {
const info = [
  {
    description: 'The sky is blue',
    mark: 'is'
  },
  {
    description: 'The sun is shining bright',
    mark: 'shining'
  },
  {
    description: 'I am trying to learn new things',
    mark: 'learn'
  }
]

  return (
    <div className="ExampleComponent">
      <h1>Help Needed</h1>
      <h2>How can I apply styles to certain sections of the displayed information?</h2>
      {info.map((data) => {
        const parts = data.description.split(data.mark);
        return (
          <p key={data.description}>
            {parts[0]}
            <span style={{ backgroundColor: "#FF0" }}>{data.mark}</span>
            {parts[1]}
          </p>
        );
      })}
    </div>
  );
}

Answer №2

There are various methods to tackle this issue. @Nick's suggestion seems practical, but don't forget to consider my proposal as well.

export default function App() {
const data = [
  {
    details: 'I had a memorable experience yesterday',
    css: true
  },
  {
    details: 'I am looking forward to today',
    css: false
  },
  {
    details: 'I need to mark my calendar for my birthday',
    css: false
  }
]

  return (
    <div className="App">
      <h1>Seeking Assistance</h1>
      <h2>How can I customize specific sections of my displayed information</h2>
      {
        data.map((detail)=>(
          <p className={detail.css ? 'my-custom-class' : ''}>{detail.details}</p>
        ))
      }
    </div>
  );
}

By following this method, you can avoid encountering

<p class="undefined">...</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to alter the height of the element

I am attempting to resize an element by dragging, similar to this example. I have created a simple directive for this purpose: @Directive({ selector: '[drag-resize]' }) export class DragResizeDirective { private dragging: boolean; const ...

The PHP on server could not be loaded by Ajax

Trying to establish a PHP connection, encountering an error and seeking assistance. The error message displayed is as follows: { "readyState": 0, "status": 0, "statusText": "NetworkError: Failed to execute 'send' on 'XMLHttpReq ...

Enhance your Highmap R or JavaScript visualization with a unique custom legend feature

Provided below is my code snippet, output$map <- renderHighchart({ region_map = hcmap("countries/nz/nz-all") highchart(type = "map") %>% hc_title(text = "Average") %>% hc_add_series_map(map = region_map, df = data1, joinBy = " ...

React and Material UI: Ensuring Proper Whitespace Handling in Strings

Exploring the use of Typography component from Material UI (https://material-ui.com/api/typography/) The main objective is to maintain the new lines and spaces in a saved string. For instance, if the string contains leading spaces and new lines, it shoul ...

Implementing a dynamic tab change functionality with props in Material UI tabs

Observing the following example: Link to Material UI Tabs Suppose I have these tab components within a widget, and I wish to include an image or icon. How can I link the icon or image so that when clicked, it changes to a specific tab without using react- ...

How can real-time data be fetched or connected to Firebase v9 in the onSubmit function?

Please provide the code in firebase-v9 to fetch the onSubmit function from firestore: const onSubmit = (formData) => { console.log(formData) db.collection('emails').add({ to: formData.to, subject: formData.subject, message: formData.mess ...

Building a Search Bar with React utilizing NextJS framework

Seeking assistance in pinpointing the issue with my code. This application is an Employee Search tool utilizing the new APP directory with NextJS. Functioning features: Includes an input field for filtering and capturing user input. The API endpoint retu ...

Utilize React JS to send emails through contact forms

I am working with a contact form in react js and I'm having trouble sending an email to the inputted mail id. As a newcomer to react js, I would appreciate some guidance on how to achieve this using the code provided below. The contact form requires e ...

What is the significance of enclosing Button within CardActions in Material-UI?

As I explored the Card documentation on MUI, I found that the Button inside the card is always enclosed within CardActions. However, I couldn't quite grasp the purpose of this tag as it wasn't clearly explained in the documentation. The only noti ...

What is the best way to apply box shadow to a particular region using CSS?

I am looking to add a box shadow using CSS, but I only want it in a certain area of the box. https://i.sstatic.net/dcFZu.png In the screenshot above, you can see that I have a blue header on my website. I would like to add a shadow to this header, specifi ...

Once an action is dispatched, React is unable to access the latest Redux state

Currently, I am in the process of familiarizing myself with React and Redux by working on a personal project. One issue I am facing is that the `isAuthed` variable is unable to access the updated Redux state after the `rest.dispatch(actions.isValidUser(js ...

Sending data to a React Dialog component using the OnClick event

I am a beginner learning React.js and currently experimenting with passing parameters to a dialog box using onclick events. <IconButton className={classes.approvebutton} onClick={() => handleDialogClick("approve",1)}> <ThumbU ...

Unable to assign values to textarea and checkbox in MVC5

I am currently facing an issue with setting values in JavaScript + jQuery in MVC 5 for textareas and checkboxes. Here is the JavaScript code I am using: document.getElementById("UpdatetxtDescription").value = "abc"; document.getElementById("Upda ...

Browser behavior for animating background-position varies

check out this interactive demo - The objective is to create a unique perspective effect while scrolling, specifically on the background. The effect functions properly on Chrome and IE7, IE8 versions; however: Issues arise with IE9, where the background ...

AWS Amplify appears to be having trouble detecting the Vite React NX monorepo

I recently set up a new NX monorepo containing 3 apps. Two of them were built with Vite, while the third one is a NextJS project. During deployment of the Vite app to AWS Amplify, it incorrectly identifies the app folder as NextJS-SSR and throws an error: ...

Position an element to the right within a div using the float property

My product page features a range of attributes that can vary from 1 to 4, each sharing a common fieldset class name. I am attempting to position two of the fieldsets side by side and the remaining ones below them in a similar layout. However, achieving thi ...

Transforming the mui stepper connection into a progress bar is simple. Each step contains individualized content to guide you through the process

Is there a way to make the MUI stepper connector act as a progress indicator? I have step content and connectors as separate divs, but I'm having trouble styling them. Any assistance would be greatly appreciated! ...

Ensure the calling object is retained during the resolution of an Angular promise

Identifying the Issue One issue arises when resolving promises in Javascript: the context switches to Window #. This means that referring back to the object resolving the promise becomes tricky because I can't access or modify its variables. The com ...

What is the method to provide function parameters without executing the function?

I'm searching for a solution to obtain a function that requires a parameter without actually invoking the function. Example of current malfunctioning code: const _validations = { userID: (req) => check('userID').isString().isUUID(&apo ...

Getting Started with Material UI's Default Components

After working with bootstrap, I decided to explore the material ui framework as well. However, when trying to use the default MUI component without customization, such as the card component, I encountered some difficulties. Here is an example of one of th ...