最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't render html tags in a template string in react.js - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Sep 25, 2018 at 9:37 connecticumconnecticum 831 silver badge6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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>
);

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

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>
);
发布评论

评论列表(0)

  1. 暂无评论