Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  134] [ 6]  / answers: 1 / hits: 58454  / 8 Years ago, sun, june 26, 2016, 12:00:00

I am new to react, and I am having a little issue. Maybe somebody can help me out.



So the issue is that I am unable to triger the element I want with onCLick function. Now I am trying to remove the navigation when



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);
navOpened.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>
);
}
}


The error I am having is



nav.js:12 Uncaught TypeError: navOpened.setState is not a function


Also if you notice some patterns that I could improve in my code, I would really appreciate the feedback.



Thank You!


More From » reactjs

 Answers
4

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.


[#61632] Friday, June 24, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jadyngraysons

Total Points: 455
Total Questions: 109
Total Answers: 98

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
jadyngraysons questions
Thu, Apr 23, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
Tue, Dec 31, 19, 00:00, 4 Years ago
;