Reputation: 23
I have the code snippet as below:
state variables:
state = {
value: 'default value',
items: [{id: 1, title: 't1'}, {id: 2, title: 't2'}]
}
inside render function:
this.state.items.map((data, key) => (
// I want to set the state of 'value' here something like this
this.setState({ value: 'somevalue' })
))
I want to map through the array and check for a particular id
in the array say, if the array contains an id = 1
, then set the state value
as t1
, similarly, if an array contains an id = 2
, then set the state of value
as t2
.
Inside map
function, we can't set the state repeatedly. What would be the alternative for this?
Upvotes: 1
Views: 3827
Reputation: 19813
You don't need to (and should not) set a state inside any loop.
In this example, you simply need to find
the matching item and, if found, set its value in the state, as shown below:
const { Component } = React
class App extends Component {
constructor(props) {
super(props)
this.state = {
value: 'default value',
items: [{id: 1, title: 't1'}, {id: 2, title: 't2'}]
}
}
handleClick = (id) => {
const found = this.state.items.find(item => item.id === id)
if (found) {
this.setState({value: found.title})
}
}
render() {
return (
<div>
value: {this.state.value} <br/>
<button onClick={() => this.handleClick(1)}>Click (1)</button>
<button onClick={() => this.handleClick(2)}>Click (2)</button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("root"))
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 1