I am trying to pass state using props and I would like to change it inverse when I press an element in another ponent. is it possible?
Header.js:
class Header extends Component {
constructor(props) {
super(props);
this.state = {
mobileOpen: false,
};
}
...
<Sidebar
open={this.state.mobileOpen}
/>
}
Sidebar.js:
function Sidebar({ open }) {
return (
<Navigation open={open} />)
}
Navigation.js:
class Navigation extends Component {
render() {
return (
<MenuItem onClick={/* change mobileOpen to false */}>text</MenuItem>
)
}
I am trying to pass state using props and I would like to change it inverse when I press an element in another ponent. is it possible?
Header.js:
class Header extends Component {
constructor(props) {
super(props);
this.state = {
mobileOpen: false,
};
}
...
<Sidebar
open={this.state.mobileOpen}
/>
}
Sidebar.js:
function Sidebar({ open }) {
return (
<Navigation open={open} />)
}
Navigation.js:
class Navigation extends Component {
render() {
return (
<MenuItem onClick={/* change mobileOpen to false */}>text</MenuItem>
)
}
Share
Improve this question
edited Jan 9, 2019 at 23:07
ReactRouter4
asked Jan 9, 2019 at 22:59
ReactRouter4ReactRouter4
1652 silver badges14 bronze badges
1
- setState is what you are looking for – Kevin He Commented Jan 9, 2019 at 23:13
1 Answer
Reset to default 4You can pass a callback from the Header
ponent as a prop to Sidebar
which in turn passes that callback to Navigation
as a prop.
In React you usually have a differentiation between presentation ponents and ponents containing logic (often referred to as "container ponents"). You can put all the states in there and and pass the necessary callbacks as props to the presentation ponents.
In your specific case, this would mean something like this:
Header.js:
class Header extends Component {
constructor(props) {
super(props);
this.state = {
mobileOpen: false,
};
}
// Create a callback to toggle the `mobileOpen` state
onMenuItemClicked = () => {
this.setState({mobileOpen: !this.state.mobileOpen});
}
render() {
return (
<Sidebar
open={this.state.mobileOpen}
/* pass callback to Sidebar */
onMenuItemClicked={this.onMenuItemClicked}
/>
);
}
}
Sidebar.js:
function Sidebar({ open, onMenuItemClicked }) {
return (
<Navigation
open={open}
/* pass callback from Header to Navigation */
onMenuItemClicked={onMenuItemClicked}
/>
);
}
Navigation.js:
class Navigation extends Component {
render() {
// finally use the callback
return (
<MenuItem onClick={() => this.props.onMenuItemClicked()}>text</MenuItem>
);
}
}