Reputation: 11
I want to add/remove class of child component's outer div from Parent Component on click of sidebar menu button(in parent component). On click of SidNav toggle button ,expand the nav and add class to the Child Component's outer div so that the content gets pushed to right.
Tried : passing ref as props - I am getting the reference but actual child dom doesnot update when class applied from Parent Component.
Any suggestions would be helpful.
Snippet :
Parent Component :
return(<Child ref={this.ref} navigation={navigation} searchParams={parsedQuery} />)
child component :
function render() {
const { navigation, classlg2, ref } = this.props;
return (
<div className="bx--grid page-content--wrapper">
<div className="bx--row">
<div
ref={ref}
className={
navigation.length > 0
? "bx--col-lg-2 bx--col-lg-14"
: "bx--col-lg-16"
}
>
{routeComponentsElements}
</div>
</div>
</div>
);
}
bx--col-lg-2
is the class that I need to add and remove on toggle of SideNav
.
If states are used to handle the className,then the content rerenders.. Example : there is ajax call in child component, when menubutton is clicked it rerenders the page going back to its home page.
Upvotes: 0
Views: 1350
Reputation: 546
Do something like this.
Parent component
this.state = {
childClass: false
}
toggleChildClass = () => {
this.setState(prevState =>({
childClass: !prevstate.childClass
}))
}
render(){
const {childClass} = this.state;
return(
<>
<button onClick={this.toggleChildClass}>Toggle Class</button>
<ChildComponent childClass={childClass} />
</>
)
}
Child Component
render(){
const { childClass } = this.props;
return(
<div
className={childClass ? "bx--col-lg-2 bx--col-lg-14"
: 'bx--col-lg-16'}>
{routeComponentsElements}
</div>
)
}
Upvotes: 0