Change style of parent element on clicking child element in React

Viewed 5517

I am new to React, I want to know how can I change the style of div with id "parent" while clicking of div with id "child".

<div id="parent"></div>

#parent{display:block;}

var Products=React:createClass({
    showHide: function(){
        // change style of parent id's "display:block" to "display:none"
    },
    render: function(){
        return (
            <div id="child" onclick={this.showHide}>ABCD</div>
        );
});
ReactDOM.render(<Products />,document.getElementById('parent'));
1 Answers

React handles this in a one-way data flow sort of way. Parent components communicate to child components through props, and child components communicate back to the parent through callback props. You need to pass a callback prop to the child component from the parent that will then update the parent's state, which then updates the style through either toggling the style prop (inline style) or toggling a CSS class using the className prop.

Here is an example where the child component updates the parent's foreground color using the style prop. onTrigger is just an example name since you didn't specify the context of why the child is updating the parent, but it can be named anything. The ChildComponent can use onTrigger to pass any data back to the parent, then the parent can handle it as needed, seen here in the handleTrigger function.

const ChildComponent = ({ onTrigger }) => (
  <div id="child" onClick={() => onTrigger("red")}>ABCD</div>
);

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);

    // Set the initial state value
    this.state = { color: "green" };

    // One of a few ways to bind the function
    this.handleTrigger = this.handleTrigger.bind(this);
  }

  handleTrigger(color) {
    this.setState({ color: color });
  }

  render() {
    return (
      <div id="parent" style={{ color: this.state.color }}>
        <ChildComponent onTrigger={this.handleTrigger} />
      </div>
    );
  }
}
Related