Reputation: 5771
I have the following component:
import React from 'react';
import Header from './header.jsx';
import Footer from './footer.jsx';
class Wrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
}
toggleWrapper() {
this.setState({open: !true});
}
render () {
const toggle = this.state.open ? 'open' : '';
return (
<section className={"wrapper " + toggle}>
<div className="inner-wrapper">
<Header action={this.toggleWrapper.bind(this)}/>
{this.props.children}
<Footer />
</div>
</section>
);
}
}
export default Wrapper;
and I am trying to update its state from its header (child) component like this:
import React from 'react';
import {render} from 'react-dom';
import {Link} from 'react-router';
import Logo from './logo.jsx';
class Header extends React.Component {
toggleNavigation() {
{this.props.action}
}
render () {
return (
<header className="header">
<button onClick={this.toggleNavigation.bind(this)}
className="menu-icon hide-for-large"
type="button">
</button>
<Logo />
<nav className="main-nav">
<li>
<Link to='/'>about us</Link>
</li>
<li>
<Link to='/projects'>projects</Link>
</li>
<li>
<Link to=''>production</Link>
</li>
<li>
<Link to=''>area director</Link>
</li>
</nav>
<i className="fa fa-envelope-o float-right contact-us-icon" aria-hidden="true"></i>
</header>
);
}
}
export default Header;
I am trying to pass "toggleWrapper" method as a prop so that I can change the state with a click event inside the header component.
However nothing happens on my screen when I click on the icon.
Upvotes: 1
Views: 1123
Reputation: 9680
Your approach is correct, but your code has two problems: first of all, your upper component's toggleWrapper
function does not actually change the state to anything other than false
(or rather, !true
). Fix it like this:
toggleWrapper() {
this.setState({open: !this.state.open});
}
Secondly the toggleNavigation
function in your child component does not actually call the function. You don't even actually need a separate function in this case, you could simply do this:
<button onClick={this.props.action} ...
Upvotes: 1