Render a string which contains components

I am newbie at reactJs and i am trying to build an app in which i get some results after searching .

My problem is that i have a component called ResultEntity and I am trying create a dynamically page without defined number of ResultEntity components.

I tried something like this

  for(var i=0 ; i<result.length ; i++)
    {
      results += "<div> <ResultEntity/> </div>";
    };
    console.log(results);
    this.setState({result: results});

And i tried to return it like ,

  return (
    <div>
      <div  dangerouslySetInnerHTML={{ __html: this.state.result }}  />
    </div>
   );

and

return (
    <div>
      <div  dangerouslySetInnerHTML={{ __html: this.state.result }}  />
    </div>
   );

but both didnt work . Any idea will be appreciated . Thank you in advance

Upvotes: 0

Views: 148

Answers (1)

Jordan Enev
Jordan Enev

Reputation: 18664

So you want to render a list of components dynamically. Here's how you can do it using .map function:

// This also can be a functional component, instead of a class
class ResultEntity extends React.Component {
  render() {
    const { item } = this.props

    return <div>{ `${item.id} - ${item.name}` }</div>
  }
}

class App extends React.Component {
  constructor(props) {
    super(props)
    
    this.state = {
      items: [
        { id: 1, name: 'Bulgaria' },
        { id: 2, name: 'Germany' },
      ]
    }
  }

  renderItems() {
    const { items } = this.state
 
    // Great explanations, why this work and it's rendered correctly:
    // https://medium.com/byte-sized-react/component-arrays-in-react-a46e775fae7b
    return items.map(item => <ResultEntity key={item.id} item={item} />) 
  }
  
  render() {
    // From React >= 16 it's possible to skip the wrapper `div`:
    // https://stackoverflow.com/a/32157488/4312466
    return <div>{ this.renderItems() }</div>
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

Upvotes: 2

Related Questions