0

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

ekclone
  • 1,030
  • 2
  • 17
  • 39
  • 1
    Possible duplicate of [How to pass data from child component to its parent in ReactJS?](https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs) – Arnaud Christ Jun 13 '19 at 08:21

1 Answers1

1

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

Daniel Doblado
  • 2,481
  • 1
  • 16
  • 24