ReactJS onClick setState to different element
Only react components have setState
method.
Working example:
import React from "react";
import ReactDOM from "react-dom";
export default class Nav extends React.Component {
constructor() {
super();
this.state = {
navStatus: "navHide"
};
this.navClose = this.navClose.bind(this);
this.navOpen = this.navOpen.bind(this);
}
navClose(e) {
e.stopPropagation();
this.setState({
navStatus: "navHide"
});
}
navOpen() {
this.setState({
navStatus: "navShow"
});
}
render() {
return(
<nav onClick={this.navOpen}>
<div id="myNav" className={this.state.navStatus}>
<div className="navClose" onClick={this.navClose}>
<object
className="navCloseBtn"
type="image/svg+xml"
data="svg/close.svg"
></object>
</div>
</div>
</nav>
);
}
Also you should bind event handlers in constructor instead of render
method.
import React from "react";
import ReactDOM from "react-dom";
export default class Nav extends React.Component {
constructor() {
super();
this.state = {navStatus: "navHide"};
}
navClose() {
var navOpened = document.getElementById("myNav");
this.setState({navStatus: "navHide"});
}
navOpen() {
this.setState({navStatus: "navShow"});
}
render() {
return(
<nav onClick={this.navOpen.bind(this)}>
<div id="myNav" className={this.state.navStatus}>
<div className="navClose" onClick={this.navClose.bind(this)}>
<object className="navCloseBtn" type="image/svg+xml" data="svg/close.svg"></object>
</div>
</div>
</nav>
);
}
}