Button in react component is not providing the function in onClick when rendering DOM. Inspecting the element shows the button element's property has f noop()
Where did my function go?
I am making a one-page React webpage that uses react-router, react-bootstrap, react-transition-group, CSSTransition and TransitionGroup. For one of my pages, I try to include Facebook's social plugins, and I want to create a button that changes the state in order to show the plugins.
I tried rendering the button without the facebook SDK and JSX, but it didn't change anything. Below, this.plugin
is defined, but I removed it for this code snippet below since it is Facebook's plugin JSX.
class WorkShop extends Component{
state={
displayPlugin: false
}
displayContent = () => {
this.setState(prevState=>({
displayPlugin: !prevState.displayPlugin
}))
}
render(){
return(
<div className="component-pages">
<div className="home-div">
<Container>
<Row>
<Col md={12}>
<div>{this.state.displayPlugin ? this.plugin : null}</div>
<button type="button" onClick={this.displayContent}>{this.state.displayPlugin ? "Close Events": "Show Events"}</button>
</Col>
</Row>
</Container>
The wrapper App component:
const App = ()=>{
return(
<Router>
<Route render={({location})=>(
<div className="global-div">
<MainNav location={location}/>
<TransitionGroup>
<CSSTransition
key={location.key}
timeout={900}
classNames="fade"
>
<Switch location={location}>
<Route exact path="/" component={Home}/>
<Route exact path="/workshops" component={WorkShop}/>
<Route exact path="/products" component={Products}/>
<Route exact path="/about" component={About}/>
</Switch>
</CSSTransition>
</TransitionGroup>
</div>
)}/>
</Router>
)
}
export default App```
The problem was in my two divs with classNames that I used in other Components. Not too sure why that would disable my onClick handler, but it did fix after I removed those divs.
<div className="component-pages">
<div className="home-div">
Need to bind this with event. See below working code.
class WorkShop extends Component {
state = {
displayPlugin: false
}
displayContent = () => {
this.setState(prevState => ({
displayPlugin: !prevState.displayPlugin
}))
}
render() {
return (
<div className="component-pages">
<div className="home-div">
<div>{this.state.displayPlugin ? this.plugin : null}</div>
<button type="button"
onClick={this.displayContent.bind(this)}>
{this.state.displayPlugin ? "Close Events" : "Show Events"}
</button>
</div></div>)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.