Reputation: 1720
I need to display differents elements on a same page using four buttons to filter it. If I click on the first button of NavigationBar component, one specific div must be displayed.
I have a Home page that must displaying the differents elements :
class Home extends Component {
constructor(props) {
super(props);
}
showContent() {
alert('ok');
}
render() {
return (
<div className="container">
<Header activeLink={['home']}/>
<p>Some texte here</p>
<NavigationBar onClick={this.showContent} firstSection="L'entreprise" secondSection="Pourquoi nous choisir ?"/>
<Footer/>
</div>
);
}
}
export default Home;
And my NavigationBar component with the four buttons :
class NavigationBar extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="navigation-bar flex row between">
<div onClick={() => {this.props.onClick()}}>
<p>{this.props.firstSection}</p>
</div>
<div onClick={() => {this.props.onClick()}}>
<p>{this.props.secondSection}</p>
</div>
<div onClick={() => {this.props.onClick()}}>
<p>{this.props.thirdSection}</p>
</div>
<div onClick={() => {this.props.onClick()}}>
<p>{this.props.fourthSection}</p>
</div>
</div>
);
}
}
export default NavigationBar;
With this code, I can display the alert('ok') when I click on the div of my NavigationBar component but I don't know how to identifying what div was clicked. If I know how to do this, I could easily display specific elements. Thank for your help.
Upvotes: 0
Views: 32
Reputation: 30082
The onClick handler will give you an event object. Pass that event object back to showContent
. You can also add identifying information to the element:
<div data-key="foo" onClick={e => this.props.onClick(e)}>
Then:
showContent(e) {
console.log(e.target.getAttribute('data-key'));
}
Upvotes: 1