Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing state of a different component - ReactJS

Tags:

reactjs

I am trying to build a simple app using react that has two components, one embedded in the other. The child component is a contracted menu and when it is clicked, it expands. I want to be able to re-contract it when the parent element is clicked, or when the child element looses focus.

This is what the parent component looks like:

import React from 'react';
import MenuBar from './_components/MenuBar.js';

var div = React.createFactory('div');
var menu = React.createFactory(MenuBar);

var HomeComponent = React.createClass({
    render: function() {
        return div({ className: 'page home current', onClick: changeChildState //change the state of the child component to false },
            menu()
        )
    }
});



export default HomeComponent;

This is what the child component looks like:

import React from 'react';

var div = React.createFactory('div');

var MenuBar = React.createClass({
    getInitialState: function() {
        return ({menuIsShowing: false});
    }
    showMenu: function() {
        return this.setState({menuIsShowing: true});
    },
    render: function() {
        var isShowing = this.state.menuIsShowing ? 'menuSlideDown' : '';
        return div({ className: 'menu-bar ' + isShowing, onClick: this.showMenu });
    }
});

export default MenuBar;

I am unsure of the correct way of doing this in react and would love some input.

like image 311
Julien Vincent Avatar asked Oct 20 '22 15:10

Julien Vincent


1 Answers

One way to achieve you goal is to hold the ChildComponent expand status in the parent component status. Pass the isExpand boolean to the child component by props. At the same time, also pass a callback to the ChildComponent to update the parent isExpand status.

var HomeComponent = React.createClass({
  getInitialState: function() {
    return ({menuIsShowing: false});
  },

  changeChildOpenStatus: function() {
    this.setState({menuIsShowing: true});
  },

  render: function() {
    return div({ className: 'page home current', onClick: this.changeChildOpenStatus },
      menu({ menuIsShowing: this.state.menuIsShowing, handleChildClicked: this.changeChildOpenStatus })
    )
  }
});

Then in the child component

var MenuBar = React.createClass({
  handleExpandClicked: function(event) {
    this.props.handleChildClicked(event);
  },

  render: function() {
    var isShowing = this.props.menuIsShowing;
    return div({ className: 'menu-bar ' + isShowing, onClick: this.handleExpandClicked });
  }

});
like image 157
IcyBright Avatar answered Oct 22 '22 21:10

IcyBright