Reputation: 1
I need some help with a class componenent in React .
I'm tring to change the class of the li after mapping the array 'list' . Could you please tell me how can I use the state in this case . When I click on the
I can do this without mapping the list vut i dont' want to repeat the code for each Composant .
Thank you very much for your help and I hope i will be understood
const list = ['Biographie', 'CV', 'Blog'];
class Navbar extends Component {
state = {
Biographie: true,
CV: false,
Blog: false,
};
show = (e) => {
list.map(item=> this.setState ({ [item]: false}))
this.setState({ [e.target.id]: true });
};
render() {
return (
<div className="navbar">
<ul className="list">
{list.map((item) => (
<li
onClick={this.show}
id={item}
className={this.state ? 'active' : ''} // How can I change class when state = true ?
>
{' '}
{item}
</li>
))}
</ul>
<Biographie info={this.state.Biographie} />
<CV info={this.state.CV} />
<Blog info={this.state.Blog} />
</div>
);
}
}
Upvotes: 0
Views: 1389
Reputation: 1
Thank you all for your answer . It is much better know :)
Thanks to you I manage to show the component but there is probably a better way Once again I repeat myself and I don't like it :) .
My code below :
{this.state.active === 'Biographie' &&
<Biographie />}
{this.state.active === 'CV' &&
<CV info={this.state.active} />}
{this.state.active === 'Blog' &&
<Blog info={this.state.active} /> }
Upvotes: 0
Reputation: 1728
Since you are setting the id in state inside show
,
you can do
className={this.state[item] ? 'active' : ''}
If you are planing on having only one active element, I suggest that you use something like this instead
state = {
active:"Biographie"
};
and
{list.map((item) => (
<li
onClick={()=>setState({active:"item"})}
id={item}
className={this.state.active === item ? 'active' : ''}
>
{item}
</li>
))}
Upvotes: 0
Reputation: 1197
Is it necessary to have state as Object? If not, then simplify, let's have state only as string...
state = null
const show = (e) => { this.setState(e.target.id) }
...
className={this.state === item ? 'active' : ''}
Upvotes: 1
Reputation: 2854
Access your state's properties using bracket notation.
{list.map((item) => (
<li
onClick={this.show}
id={item}
className={this.state[item] ? 'active' : ''}
>
{' '}
{item}
</li>
))}
Upvotes: 0