0

I cannot pass a parent's state to its child component.

I've tried passing the whole parent's state to the child, however, the content of the state itself was undefined. Also, I've tried similarly by using props, but it did not work well either.


//parent.js

state = {
  messages: [],
  roomId: this.props.navigation.getParam('roomId')
}

renderImageAction = () => {
  return <ImageAction roomId={this.state.roomId} />
}

return(<GiftedChat renderActions={this.renderImageAction}/>)

//child.js
DataBase.saveImage(this.props.roomId).then(alert('done'));  

I expect that the state or the value will be passed to the child component, and there the value will be available.

西田龍
  • 78
  • 1
  • 6

1 Answers1

0

This is the easiest way to understand this thing to my perspective. Hope this helps.

class Parent extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      fieldVal: ""

    }

  }

  onUpdate = (val) => {

    this.setState({

      fieldVal: val

    })

  };

  render() {

    return (

      <div>

        <h2>Parent</h2>

        Value in Parent Component State: {this.state.fieldVal}

        <br/>

        <Child onUpdate={this.onUpdate} />

        <br />

        <OtherChild passedVal={this.state.fieldVal} />

      </div>

    )

  }

}



class Child extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      fieldVal: ""

    }

  }

  update = (e) => {

    console.log(e.target.value);

    this.props.onUpdate(e.target.value);

    this.setState({fieldVal: e.target.value});

  };

  render() {

    return (

      <div>

        <h4>Child</h4>

        <input

          type="text"

          placeholder="type here"

          onChange={this.update}

          value={this.state.fieldVal}

        />

      </div>

    )

  }

}

class OtherChild extends React.Component {

  render() {

    return (

      <div>

        <h4>OtherChild</h4>

        Value in OtherChild Props: {this.props.passedVal}

      </div>

    )

  }

}

React.render(

  <Parent />,

  document.getElementById('react_example')

);
Tanmoy Sarker
  • 1,176
  • 2
  • 14
  • 38