eersteam eersteam - 2 months ago 13
React JSX Question

React JS one way data flow confusion

This is the jquery solution that i want to implement using reactJS

var offCanvass = function() {
$('body').on('click', '.js-fh5co-nav-toggle', function(event) {

var $this = $(this);

$('#fh5co-offcanvass').toggleClass('fh5co-awake');
$('#fh5co-page, #fh5co-menu').toggleClass('fh5co-sleep');

if ($('#fh5co-offcanvass').hasClass('fh5co-awake')) {
$this.addClass('active');
} else {
$this.removeClass('active');
}
event.preventDefault();

});
};


What I am able to do is : By using states and classnames i can change the CSS classes of a particular component on an event inside that component.

var classNames = require('classnames');
export default class App extends React.Component {

render() {
var navClass = classNames({
'js-fh5co-nav-toggle': true,
'fh5co-nav-toggle': true,

});
return (
<div>
<Offcanvas/>
<Menu navClass={navClass}/>
<Page/>
</div>
);
}
}

export default class Menu extends React.Component {
constructor(){
super();
this.state={
isPressed: false,
};
}

isPressed(){
if(!this.state.isPressed){
this.setState({isPressed: true});
}else{
this.setState({isPressed: false});
}
}

render() {
var navClass = classNames(this.props.navClass, {
active: this.state.isPressed
});
return (
<div id="fh5co-menu" class="navbar">
<div class="container">
<div class="row">
<div class="col-md-12">
<a class={navClass} data-toggle="collapse" onClick={this.isPressed.bind(this)} data-target="#fh5co-navbar" aria-expanded="false" aria-controls="navbar"><span></span> <i></i></a>
<a href="/index" class="navbar-brand"><span>dota groove<a class=""></a></span></a>
</div>
</div>
</div>
</div>
);
}
}

export default class Canvas extends React.Component {


render(){
return(
<div id="fh5co-offcanvass">
<ul>
<li class="active"><a href="" data-nav-section="home">Home</a></li>
<li><a href="" data-nav-section="login">Register</a></li>
<li><a href="" data-nav-section="clients">Login</a></li>
</ul>
</div>
);
}
}


What I want to do : Use an event from one component to trigger the classname change of another component which are not in top down hierarchy. This is my component structure.

-app
-canvas ->classname apends here
-menu ->if click event occurs here
-page

Answer

Would the following pattern work for you?

A child component (menu) changes the state of its parent (app) via a click event. Then the parent sends the updated state to its another child (canvas) via a prop.

Here is a a short codecademy exercise that describes this pattern: https://www.codecademy.com/en/courses/react-102/lessons/child-updates-sibling/exercises/child-updates-sibling-intro