Reputation: 321
I want to dynamically update state CurrentIndex whenever I select a user.Right now I am hardcoding it to 0. I want to change that.
I want to update currentIndex whenever I click on the list of users.
SidePanel contains arrays of user and its outputting firstname,lastname
class Home extends Component {
state = {
loadUsers: [],
currentIndex: 0,
};
async componentDidMount() {
const res = await axios.get("http://localhost:5000/users");
this.setState({ loadUsers: res.data });
}
render() {
return (
<Fragment>
<div className="row">
<div className="col-md-3" style={{ backgroundColor: "#303F9F" }}>
<Typography variant="h6">List all Counsellors</Typography>
{this.state.loadUsers.map((user) => {
const { _id, firstname, lastname } = user;
return (
<div key={_id}>
<SidePanel
id={_id}
firstname={firstname}
lastname={lastname}
/>
</div>
);
})}
</div>
<div className="col-md-4">
{this.state.loadUsers.length > 1 && (
<div>
<MiddlePanel
user={this.state.loadUsers[this.state.currentIndex]}
/>
</div>
)}
</div>
</div>
</Fragment>
);
}
}
Upvotes: 1
Views: 1162
Reputation: 202686
Create a handler to consume the mapped index and pass/attach handler where you need it.
class Home extends Component {
state = {
loadUsers: [],
currentIndex: 0,
};
...
incrementIndex = (currentIndex) => (e) => this.setState({ currentIndex });
render() {
return (
<Fragment>
<div className="row">
<div className="col-md-3" style={{ backgroundColor: "#303F9F" }}>
...
{this.state.loadUsers.map((user, index) => {
const { _id, firstname, lastname } = user;
return (
<div key={_id}>
<SidePanel
id={_id}
firstname={firstname}
lastname={lastname}
onClick={incrementIndex(index)} // <-- pass handler to Panel
/>
</div>
);
})}
</div>
...
</div>
</Fragment>
);
}
}
Upvotes: 2