I am trying to extract part of a string value that includes the Trade Mark in react and apply className or inline style so i can change the style, but the result i am getting from this code is [object object]
const dataTm = <span style={{ border: '2px black solid' }}>™</span>
const changeFormat = (item) => {
const replaceTm = item?.name.replace('™', `${dataTm}`)
return ReactHtmlParser(replaceTm)
}
const menu = () =>{
return(
<Link>
{item?.name.includes('™') ? changeFormat(item) : item?.name}
<Link>
)}
CodePudding user response:
String#replace
returns a string - it converts everything what passed in into a string as well. And if you try to convert an object (and this is what JSX
is - an object), you will get [Object object]
in return.
You have to slightly modify your code, the most important difference is to change the dataTm
variable to a string, so it can be properly understood by the String#replace
function.
const item = {
name: 'abc™abc',
};
export default function App() {
const dataTm = "<span style='font-size:32px;color:red'>™</span>";
const changeFormat = (item) => {
const replaceTm = item?.name.replace('™', dataTm);
return ReactHtmlParser(replaceTm);
};
return (
<div>{item?.name.includes('™') ? changeFormat(item) : item?.name}</div>
);
}
https://codesandbox.io/s/bitter-frost-5fk6je?file=/src/App.js
The code above and in the codesandbox it's just a minimal example. In your code sample you should just wrap dataTm
with quotes and adjust the styles a bit and it should work properly.