0

Let's say I'm having the following component:

class LeftPanel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {abc: 'xyz'};
  }
render() {
  return (
    <div>
     <Thumb src={img1}/>
     <Thumb src={img2}/>
   </div>);
 }

Inside the component, there's an inner component called Thumb that goes like there:

class Thumb extends React.Component {
  constructor(props) {
   super(props);
   this.state = { src: props.src };
  }

  render() {
   return (
    <div>
      <img src={this.state.src}></img>
    </div>
   );
  }

}

Question: Can I modify the state of LeftPanel Component inside Thumb? If yes, how?

Cesar Jr Rodriguez
  • 1,691
  • 4
  • 22
  • 35
  • 1
    Yes, add a method to `LeftPanel` that modifies the state and then pass that method as a prop to `Thumb`. There's already [questions that ask this](http://stackoverflow.com/questions/35537229/how-to-update-parents-state-in-react). – Jack Jan 08 '17 at 03:05
  • 1
    Also why are you copying props to state in Thumb? This looks like a problematic pattern, you shouldn't do this. – Dan Abramov Jan 08 '17 at 14:03
  • 1
    I believe your question is answered in this document. Have you had a chance to read it yet? https://facebook.github.io/react/docs/lifting-state-up.html – Dan Abramov Jan 08 '17 at 14:04
  • @DanAbramov I'm starting to use React, thank's for the advice. I didn't knew that is a bad pratice passing values to the state that way. – Cesar Jr Rodriguez Jan 08 '17 at 17:02

1 Answers1

2

create a method in Left panel to handle the event. Then pass the method to the child component.

Now if you want to pass data to the parent I would recommend a library like flux or redux. since redux has a global state it is accessible to all components. When you modify the global state to whole application is rerendered with the new state. The new state is visible by all components.

class LeftPanel extends React.Component {
  constructor(props) {
    super(props);
    this.modifyLeftpanel = this.modifyLeftpanel.bind(this);
    this.state = {abc: 'xyz'};
  }

  modifyLeftpanel(newvar){
      //Do something with newvar
  }
render() {
  return (
    <div>
     <Thumb src={img1} modifyLeftPanel={this.modifyLeftpanel}  />
     <Thumb src={img2} modifyLeftPanel={this.modifyLeftpanel} />
   </div>);
 }

here is the thumb

class Thumb extends React.Component {
  constructor(props) {
   super(props);
   this.state = { src: props.src };
   this.doSomething = this.doSomething.bind(this);
  }

  doSomething(){
       this.props.modifyLeftpanel(10);
  }

  render() {
   return (
    <div>
      <img src={this.state.src}></img>
      <button onClick={this.doSomething}>Modify Parent</button>
    </div>
   );
  }
Luke101
  • 63,072
  • 85
  • 231
  • 359