I am using axios to read data from my backend. The data is a string similar to "phone number: {enter phone number here}"
.
I want to apply css to where ever 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 a couple of ways I want to apply the data.
Inside the value of a TextField
<TextField
rows={12}
multiline
value={testString}
></TextField>
Inside a div
<div contenteditable="true">{testString}</div>
Instead of applying the css, it just displays the css as a string
hello this is my <span style={{color: 'red'</span></span>>test</span> string
CodePudding user response:
What do you want to do is clear. You should get the string and show it in JSX Element
like this:
let testString = ... ; // what ever you get from request
<div>hello this is my <span className="red-color">{testString}</span> string</div>
OR:
let testString = ... ; // what ever you get from request
<div>hello this is my <span style={{color:"red"}}>{testString}</span> string</div>
also, you can use backticks to put variables in your strings
CodePudding user response:
This problem can be solved in two ways and the solutions are as follows,
Solution 1 : Using 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 the name suggests, the dangerouslySetInnerHTML
should be used with caution. If the string is received from an untrusted source, then it is better to avoid this method as it is prone to XSS attacks. Read more about it here
Solution 2 : Using 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 gets the index of the opening {
and closing }
braces from the string and applies formatting for that enclosed substring alone. This approach is suitable if the string contains only a single bracket enclosed block which needs to be formatted.
The sandbox with the working solutions can be found here