ekclone
ekclone

Reputation: 1092

Passing object to parent state from child

Is there any way I can push an object to the parent props from the child component?

Upvotes: 0

Views: 41

Answers (1)

Daniel Doblado
Daniel Doblado

Reputation: 2848

You can pass a function from the parent to the child that can set the state of an object in the parent.

import React, { Component } from 'react';
import { render } from 'react-dom';

const Child = ({saveObj}) => (
  <div
    onClick={() => {
      saveObj({test: "test"})
    }}
  >
    Click to set obj
  </div>
) 

class App extends Component {
  constructor() {
    super();
    this.state = {
      obj : null
    };
  }

  render() {
    return (
      <div>
        Obj is: {JSON.stringify(this.state.obj)}
        <p>
          <Child saveObj={obj => {this.setState({obj})}} />
        </p>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

Live Example: https://stackblitz.com/edit/react-snivhc

Upvotes: 1

Related Questions