Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid dangerouslySetInnerHTML?

I wrote a React component which renders rating and visualizes it with stars. But I had to use dangerouslySetInnerHTML for that. How could I rewrite component with better code style and without dangerouslySetInnerHTML? Thank you for any help.

export default class BookRating extends React.Component {
  renderStars = () => {
    let result = '';

    for(let i=1; i<=5; i++) {
      this.props.rating >= i
      ? result += '<div class="fa fa-star checked"></div>'
      : result += '<div class="fa fa-star"></div>'
    }

    return result;
  }

  render () {
    return (
      <div className="rating" dangerouslySetInnerHTML={{ __html: this.renderStars() }} />
    );
  }
}
like image 239
Sergey Avatar asked Apr 20 '26 17:04

Sergey


1 Answers

You can render multiple elements with an array, rather than a string:

export default class BookRating extends React.Component {
  renderStars = () => {
    let result = [];

    for(let i=1; i<=5; i++) {
      this.props.rating >= i
      ? result.push(<div key={i} class="fa fa-star checked"></div>)
      : result.push(<div key={i} class="fa fa-star"></div>'
    }

    return result;
  }

  render () {
    return (
      <div className="rating">{this.renderStars()}</div>
    );
  }
}

As Quentin and Emile pointed out, you can write this function in one line, like so:

renderStars = () => Array(5).fill(0).map(_, i => <div className={`fa fa-star${this.props.rating > i ? ' checked' : ''}`}/>)
like image 182
Kobe Avatar answered Apr 22 '26 06:04

Kobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!