Can We Style Inside A Const In React

Viewed 432

I am new to react , can i style inside a const

Here is my code

const initialStudentCounter =
    'Students' + ' ' +  JSON.stringify(studentCountInitial);

I need to style this "JSON.stringify(studentCountInitial)"

I tried this way , but didn't work

const initialStudentCounter =
    'Students' + ' ' +  <span style={color : 'red'}>JSON.stringify(studentCountInitial)</span> ;

Can some one help me please

3 Answers

You don't need JSON.stringify in JSX. You do need to insert this into your JSX with a surrounding element. You shouldn't need the + for concatenating strings anymore either.

export default function App() {
  const studentCountInitial = 4;
  const initialStudentCounter = <div>Students <span style={{color : 'red'}}>{studentCountInitial}</span></div>;

  return (
    initialStudentCounter
  );
}

In React, you need to use double curly brackets (The first set of brackets is telling the compiler that this is Javascript, the second set is telling the compiler that this is an object.) when styling elements. Also, surround your element with a string.

Code:

const initialStudentCounter =
    'Students' + ' ' + `<span style={{ color : 'red' }}>${JSON.stringify(studentCountInitial)}</span>`;

There are at least two problems here:

  • You're concatenating a string with a JSX element.
  • Your style attribute's value is missing a pair of curly braces for opening and closing an object (the first pair merely lets you use JS syntax).
const initialStudentCounter = <p>Students <span style={{color : 'red'}}>{JSON.stringify(studentCountInitial)}</span></p>;

I also suspect that studentCountInitial is just a plain number and thus it probably doesn't need to be stringified. So you can probably just do this...

const initialStudentCounter = <p>Students <span style={{color : 'red'}}>{studentCountInitial}</span></p>;

If you really need to then convert that JSX element to a string, you could use something like ReactDOMServer.renderToStaticMarkup(), but that's likely unnecessary.

Related