Styling Text with CSS

I am currently using axios to fetch data from my backend. The data consists of a string format similar to

"phone number: {enter phone number here}"
.

My goal is to add CSS styling wherever there is a curly brace.

let testString = "hello this is my {test} string";
testString = testString.replaceAll("{", "<span style={{color: 'red'}}>");
testString = testString.replaceAll("}", "</span>");

There are different ways I plan to incorporate the data:

1. Inside the value of a TextField

<TextField
rows={12}
multiline
value={testString}
></TextField>

2. Inside a div

<div contenteditable="true">{testString}</div>

However, instead of applying the intended CSS, it simply displays it as a string.

hello this is my <span style={{color: 'red'</span></span>>test</span> string

Answer №1

There are two ways to tackle this issue and here are the solutions:

Method 1 : Leveraging dangerouslySetInnerHTML

export default function App() {
  let text = "The {text in here} will be color coded";

  return (
    <div>
      <div
        className="solution-1"
        dangerouslySetInnerHTML={{
          __html: text
            .replace("{", `<span style=color:red>`)
            .replace("}", `</span>`)
        }}
      ></div>
    </div>
  );
}

As implied by the name, using dangerouslySetInnerHTML requires caution. It is advisable to refrain from using this method if the string originates from an untrusted source, as it can make the application vulnerable to XSS attacks. Further information on this topic can be accessed here

Method 2 : Employing substring offset

export default function App() {
  let text = "The {text in here} will be color coded";

  let i = [];
  text.replace(/[{.+?}]/g, (match, offset, string) => {
    i.push(offset + 1);
  });

  let formattedText = () => {
    return (
      <>
        <span>{text.substring(0, i[0] - 1)} </span>
        <span style={{ color: "red" }}>{text.substring(i[0], i[1] - 1)}</span>
        <span>{text.substring(i[1], text.length)}</span>
      </>
    );
  };

  return (
     <div className="solution-2">{formattedText()}</div>
  );
}

The second approach involves identifying the index of the opening { and closing } braces within the string, allowing for formatting of the enclosed substring exclusively. This method is suitable when dealing with a single bracket-enclosed block that requires formatting.

A live demonstration showcasing the working solutions is available here

Answer №2

Your objective is clear - you need to retrieve a string and display it within a JSX Element.

For example:

let testString = ... ; // receive data from request
<div>hello this is my <span className="red-color">{testString}</span> string</div>

OR:

  let testString = ... ; // receive data from request
<div>hello this is my <span style={{color:"red"}}>{testString}</span> string</div>

You can also use backticks to insert variables into your strings.

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

I'm not sure how to use the global .container CSS style in Next.js for multiple pages

I'm currently diving into the world of React and Next.js, tackling a project with Next.js. I've set up a global CSS file with a .container style definition which I imported in my _app.js file. However, I'm unsure how to apply this global sty ...

In React, I am currently working on implementing a feature that will allow the scene camera to move as the user scrolls

I'm currently working on incorporating a feature to enable movement of the scene camera when scrolling in React. However, as I am relatively new to using this library, I am unsure which implementation approach would be most suitable for achieving this ...

Guide to setting up npm pug-php-filter in conjunction with gulp

I'm having trouble setting up pug-php-filter (https://www.npmjs.com/package/pug-php-filter) with gulp in order to enable PHP usage in my Pug files. Any assistance would be greatly appreciated. ...

React does not support having two :focus selectors on a single JSX element

I'm working with a React script that includes a specific element. I want to apply more than one :focus-within selector in CSS, but for some reason only the dropdown selector is being expressed when I focus on the element. Here's the code: React J ...

Tips for updating the background color of a select option

I'm looking to customize the background color of select options in my Bootstrap 4 form. Can anyone provide guidance on how to achieve this? `` <div class="form-group "> <select class="form-control > <option va ...

Eliminate empty space in the table cell

I am working with a table that looks like this: <table> ... <td> <div class="btn-group btn-group-sm"> <button class="btn btn-info mini"><span class="glyphicon glyphicon-duplicate"></span></button&g ...

Transferring Data through the POST Method

Is there a way for me to send just one variable using the post method? I have retrieved the $row[id] from the database and need to include it in the form submission. We know how to send user input using dfs, but what about sending the specific $row[id] v ...

What is the CSS method for styling a color label on an active input box?

I am trying to achieve a specific effect where the label changes color when the input box is in focus. However, my current CSS code does not seem to be working as expected. Can someone please explain why and provide a solution to fix this issue? .test-l ...

Can conditional statements be utilized within a React component?

Using Material UI, the CardHeader component represents the top part of a post. If the post is created by the user (isUser = true), I would like to display two buttons on the post. Is this achievable? <CardHeader avatar={ <Avatar sx={{ ...

Managing HTTP errors using async/await and the try/catch block in a React application with TypeScript

Below is a snippet of code I am working with! import React, { useState } from "react"; function App() { const [movies, setMovies] = useState([]); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState<string ...

Unable to transfer card from the top position in the screen

Utilizing Tailwind (flowbite) for the frontend of my project, I encountered an issue where the Navbar was overlapping the Card. I attempted using mt-8 to resolve the problem, but it did not yield significant changes. What adjustments should I make to achi ...

Prevent the crawling of HTML segments by utilizing HTML-XSL parsing techniques

I am currently working with Watson Explorer FC 11.0.2 and I am facing a challenge in excluding certain HTML tags from the Watson crawlers. I am using an XSLT parser to extract metadata, title, and body from an HTML page located at the following path: "/h ...

Utilizing useContext data in conjunction with properties

When using useContext in a component page, I am able to successfully retrieve data through useContext within a property. customColorContext.js import { createContext, useEffect, useState, useContext } from 'react'; // creating the context objec ...

Switch between display modes by clicking using collections

I am trying to figure out how to create a function that will only show content for the specific element in which my button is located. Currently, when I click the button it shows content for all elements with the 'one' class, but I want it to dis ...

What are the best techniques for implementing opacity in styled components within react-native?

Trying to achieve a lighter background color using opacity in react-native with styled-components. I'm looking to make the background appear faded by adjusting the opacity level, but nothing seems to happen when I apply my code. Any suggestions on h ...

`When a link is clicked, show one div overlapping another.`

Is it possible to have one div display over another when a link is clicked? Here is the HTML and CSS code: <div id="desc" class="desc">some text</div> <div id="awards" class="awards">some other text</div> <a href="#">click< ...

Redux is calling for action, but it is failing to be executed

I have been working on a login application and everything is functioning correctly. However, I noticed that all the states are lost when the page is refreshed. Upon logging in, a token is sent from the backend which I store locally. I then call the "loadUs ...

Tips for live streaming LLM data from FastAPI to React?

I am trying to implement streaming of an LLM (ollama) response using fastapi and react. Initially, I was able to retrieve a response from the LLM without any issues. However, as soon as I attempted to stream the response, an error cropped up in my react ap ...

Using Material-UI in a project without the need for create-react-app

My objective is to utilize Material-UI without relying on create-react-app, as I feel that it abstracts too much and hinders my learning process. Unfortunately, all the instructions I have come across are centered around create-react-app. I am aiming to s ...

Generate a div element dynamically when an option is selected using AngularJS

I'm having trouble dynamically creating div elements based on the selected option value, but for some reason ng-repeat isn't working as expected. Can you help me figure out what I'm missing? Here's the HTML snippet I'm using - &l ...