4

Googled it but still can't realize how to render html tags in a template string in React:

return (
  <p className="text-left m-3">
     {this.state.movies ? `Showing <strong>`${this.state.movies.length}</strong`> : 
                          `DB is empty`
     }
  </p>
);

Is there any elegant "react way" to fix it?

3 Answers 3

4

You can simply make use of span to wrap the elements instead of having them returned as a string

return (
  <p className="text-left m-3">
     {this.state.movies ? <span>Showing <strong>{this.state.movies.length}</strong></span> : 
                          <span>DB is empty</span>
     }
  </p>
);
Sign up to request clarification or add additional context in comments.

Comments

1

Few things you are doing wrong in your code. 1. Template literals do not work directly in return, you need to add template literals inside {test ${value}} 2. You have syntax error here i.e., template literal should end after ending tag element of strong

 `Showing <strong>`${this.state.movies.length}</strong`>

Do it this way

return (
  <p className="text-left m-3">
     {this.state.movies ? <span>{`Showing <strong>${this.state.movies.length}</strong>`}</span> : 
                          <span>{`DB is empty`}</span>
     }
  </p>
);

OR

Assign template literals to a local variable and call it in return

render(){
   const text = `Showing <strong>${this.state.movies.length}</strong>`;
   const text1 = `DB is empty`;
   return (
     <p className="text-left m-3">
     {this.state.movies ? <span>{text}</span> : <span>{text1}</span>}
     </p>
   )
}

Comments

0

You can simply use like this:

return (
  <p className="text-left m-3">
     Showing 
   {this.state.movies &&
    // I would also make sure its length
     this.state.movies.length > 0 &&
     // to make sure not to print 0
     <strong>this.state.movies.length</strong> 
     || 'DB is empty'}
  </p>
);

Comments

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.