jose suarez
jose suarez

Reputation: 31

How to Update content using ReactJS

I'm new in React and I trying to build a simple list of items clickable to get data and update the DOM, I have a list of links on render()

 const listNews = this.state.news.map((item, i) => 
        <ListGroupItem  key={i} className="font-size-1 text-left">
            <a href='#' onClick={() => this.getInfoNews(i)}>{item.title}</a>
        </ListGroupItem>  
  );

the function "getInfoNews(i)" have this piece of code to display the data into DOM

getInfoNews(i){
    var content = {
        news : this.state.news[i]
      }

      console.log(content.news)

  if(content.news === undefined){
      return (
          <Card>
              <CardBody>
                  <CardTitle>Card Title</CardTitle>
                  <CardSubtitle>Card subtitle</CardSubtitle>
                  <CardText>Some quick example text to build on the card title and card's content.</CardText>               
              </CardBody>
          </Card>
        )
  }else{
       return (
          <Card>
            <CardBody>
                <div className="container">
                    <img src={content.news.urlToImage} className="w-100" />
                    <CardTitle>
                      <div className="bottom-left font-size-2 bg-dark w-50 p-2 text-uppercase text-left">{content.news.title}</div>
                    </CardTitle> 
                </div>
                <CardSubtitle className="text-right text-dark font-size-1 mr-4">
                    by {content.news.author ? content.news.author : "Anonymous"} , published at {content.news.publishedAt}
                </CardSubtitle>
                <CardText className="text-dark font-size-2 mt-4">
                  {content.news.description} <a href={content.news.url} target="_blank">read more</a> 
                </CardText>
            </CardBody>
          </Card>
        )
  }

}

Work perfect on load first time, but dont work once clicked on every link, the data is loaded but the DOM dont update, some one can help me ? thanks!

Upvotes: 0

Views: 1791

Answers (1)

Jackyef
Jackyef

Reputation: 5012

React re-renders whenever there is an update to either the state or the props.

For example, you can load new data from API, and then do this.setState to update the component state. Then, react will re-render the component automatically.

Upvotes: 1

Related Questions