1

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

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i used what you suggested and i get undefined value for const replaceTm ``` const dataTm = '<span style=font-size:32px;>™</span>' const changeFormat = (item) => { const replaceTm = item?.name.replace('™', dataTm) console.log(dataTm) console.log(replaceTm) return ReactHtmlParser(replaceTm) }```
from my understanding .replace just change a string with a new string, i am not sure why we use dataTm just by itself there
@Afra Hmm, it works well for me. Please check the updated codesandbox.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.