Home > Software design >  Run function on load on .map element in React
Run function on load on .map element in React

Time:06-21

I have a set of components being rendered from a .map() function in my React application.

I have a function that fires on element's onClick which works great. However, I also need to fire this function automatically on a specific element when the page loads.

Here's a rather rudimentary example: https://codesandbox.io/s/ecstatic-cartwright-ve84yt.

So in the example, I have an array of 5 names, when you click the card, the field at the bottom displays the name of the selected card. What I'm trying is to pre-select (Without using setState's initial value) one of the cards.

CodePudding user response:

If you want to preselect. You have to use componentDidMount lifecycle react method. It will be fired after your component will be rendered.

  componentDidMount() {
    this.setState({
      selectedName: names[1]
    });
  }

CodePudding user response:

If the selectedName is not initialize, select first name in the list.

Selected Name: {this.state.selectedName || names[0]}

https://codesandbox.io/s/little-hill-wv4200

  • Related