Search code examples
reactjsecmascript-6state-saving

React.js, correct way to iterate inside DOM


Im new in ReactJS...

I have a project with the following class components structure:

index.js
  --app
    --chat
  --header
  --left
  --right

In the chat.js component, I make a google search with the api to retrieve images based on specific keyword... My intuitive solution was:

this.client.search("cars")
                .then(images => {
                    for(let el of images) {
                    ReactDOM.render(<img src="{{el.url}}" syle="{{width: '100%'}}" />, document.querySelector('#gimages'));
                    }
                });

It is correct? Or I may to use Components with stored states with flux (redux)?


Solution

  • Perhaps a simpler more conventional use of react would achieve what your require?

    You could follow a pattern similar to that shown below to achieve what you require in a more "react-like" way:

    class Chat extends React.Component {
    
      constructor(props) {
        super(props)
        this.state = { images : [] } // Set the inital state and state
                                     // model of YourComponent
      }
    
      componentDidMount() {
    
        // Assume "client" has been setup already, in your component
    
        this.client.search("cars")
        .then(images => {
    
          // When a search query returns images, store those in the
          // YourComponent state. This will trigger react to re-render 
          // the component
          this.setState({ images : images })
        });
      }
    
      render() {
    
        const { images } = this.state
    
        // Render images out based on current state (ie either empty list, 
        // no images, or populated list to  show images)
        return (<div>
            { 
              images.map(image => {
                  return <img src={image.url} style="width:100%" />
              })
            }
        </div>)
      }
    
    }
    

    Note that this is not a complete code sample, and will require you to "fill in the gaps" with what ever else you have in your current Chat component (ie setting up this.client)