Reputation: 601
I want to hide a particular element in react list.
This is how state looks like:
this.state = {
lgShow: false,
list: [
{ id:1, hidden: true },
{ id:2, hidden: true }
]
};
This is how component looks like:
props.list.map( result => (
<button onClick={toggle(result.id)}> Hide </button>
{ result.hidden && <div id={result.id}> .... </div> }
))
I want to write function toggle which searches the id in App.js and change value of hidden for that id, something like this(Although I'm not able to setState() in this case).
let toggle = id => {
this.state.list.filter( val=>val.id===id ? val.hidden=!val.hidden )
}
Upvotes: 0
Views: 2391
Reputation: 4323
let toggle = id => {
let newList = list.map(val => val.id === id ? { id: val.id, hidden: !val.hidden} : val);
this.setState({list: newList})
}
You can do this inside toggle to setState()
Upvotes: 2
Reputation: 13956
You need to use setState
method to update the state of list
, that is the only way to update DOM in react. Every time a state/prop changes only then the DOM will re-render. This is how React works.
I have updated the toggle
function, it now iterates over the list
array, and toggle the id
hidden flag passed in toggle(id)
param.
class App extends React.Component {
constructor() {
super();
this.state = {
lgShow: false,
list: [
{ id:1, hidden: true },
{ id:2, hidden: true }
],
};
} // end of constructor
toggle = (id) => {
const list = this.state.list.map(item => {
if (item.id === id) {
return { ...item, hidden: !item.hidden };
}
return item;
})
this.setState({ list })
} // end of toggle
render() {
return (
<div>
{list.map( result => (
<>
<button onClick={() => toggle(result.id)}> Hide </button>
{result.hidden && <div id={result.id}>....</div>}
</>
))}
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
P.S: I didn't run this code, just did a dry run on notepad.
Upvotes: 1