I have a array that for every item in the array a drop down list is dynamically generated. Right now each drop down list share the same toggle boolean so they all open and close
I can recommend the following pattern to toggle dynamically created elements:
// Item.js
class Item extends React.Component {
handleClick = () => {
const { id, onClick } = this.props;
onClick(id);
}
render() {
const { isOpen } = this.props;
return (
)
}
}
// App.js
class App extends React.Component {
static getDerivedStateFromProps(nextProps, prevState) {
const { items } = nextProps;
if (items !== prevState.prevPropsItems) {
return { items, prevPropsItems: items };
}
return null;
}
state = {
prevPropsItems: [],
items: []
}
toggleItem = id => this.setState(prevState => {
const items = prevState.items.map(item => {
if (item.id === id) {
return { ...item, isOpen: !item.isOpen }
} else {
return item;
}
});
return { items }
})
render(){
const { items } = this.state;
return (
{items.map(item => )}
);
}
}
// AppContainer.js
const itemsFromRedux = [
{ id: '1', isOpen: false },
{ id: '2', isOpen: false },
{ id: '3', isOpen: false },
]
ReactDOM.render( , document.getElementById('root'))