Kevin
Kevin

Reputation: 341

How to pass state from child component to parent component?

I have the parent component called App, and a child component called Left.

Left component has a couple of components called Settings and NotesList

class Left extends Component {
  constructor() {
    super();

    this.state = { isAddNewNoteClicked: false };
  }

  render() {
    return (
      <section>
        <Settings onNew={this.onNewNote.bind(this)} />
        <NotesList newNote={this.state.isAddNewNoteClicked} />
      </section>
    );
  }

  onNewNote = (isAddNewNoteClicked) => {
    this.setState({ isAddNewNoteClicked });

    {/* SEE EDIT */}
    {/* this.props.onNewNote(this.state.isAddNewNoteClicked); */}

    {/* SEE EDIT #2 */}
    this.props.onNewNote(isAddNewNoteClicked);
  }
}

Settings component has a button that will pass isAddNewNoteClicked as true when clicked.

the state is being passed up to Left without a hitch, but my problem is passing isAddNewNoteClicked from Left to App.

<App /> looks like this

class App extends Component {
  constructor() {
    super();

    this.state = { isAddNewNoteClicked: false };
  }

  onNewNote = () => {
    console.log('test');
  }

  testFunction(a) {
    console.log('test', a);
  }

  render() {
    return (
      <main className="App">
        <Left onNew={this.testFunction.bind(this)} />
        <Right isAddNewNoteClicked={ this.state.isAddNewNoteClicked } />
      </main>
    );
  }
}

EDIT

so I added this.props.onNewNote(this.state.isAddNewNoteClicked); to the onNewNote function on my <Left /> component and it's now calling that function, but the state on the `' is not being updated...

EDIT #2

instead of this.props.onNewNote(this.state.isAddNewNoteClicked); I added the variable itself instead of that from the state and it's working now.

Upvotes: 0

Views: 87

Answers (3)

AishuSuhan P
AishuSuhan P

Reputation: 123

For this, Parent has send the value to its child as props. so, we are get that in our child component by props.

By the following way.

this.props.onNewNote(this.state.isAddNewNoteClicked);

Upvotes: 0

Kevin
Kevin

Reputation: 341

Okay so adding this line

this.props.onNewNote(isAddNewNoteClicked);

on the onNewNote() function on my <Left /> fixed the issue.

Hope it helped someone else!

Upvotes: 0

Gabriel Ferrarini
Gabriel Ferrarini

Reputation: 961

Your Left component is not calling the onNew function that was passed to it via props from App. This part

onNewNote = (isAddNewNoteClicked) => {
  this.setState({ isAddNewNoteClicked });
}

will only set the state for Left until you call this.props.onNew()

Edit

On Left

onNewNote = (isAddNewNoteClicked) => {
  this.setState({ isAddNewNoteClicked });
  this.props.onNew(isAddNewNoteClicked); // Notice you calling it "onNew", not "onNewNote"
}

on App

testFunction(isAddNewNoteClicked) {
  this.setState({ isAddNewNoteClicked })
}

Upvotes: 1

Related Questions