Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call setState from another Component in ReactJs

I have two react components and I'd like to call setState to set a state in the one Component but called in the other one. How do I do that?

like image 831
Dennis Schweizer Avatar asked Mar 06 '19 17:03

Dennis Schweizer


People also ask

How do you call setState from another component React?

You can't directly call setState on a parent component from a child component because the updating of a component state is restricted to the current component. To handle this, simply pass a function from the parent to the child that contains setState .

How do you access a state from another component?

To pass the state into another component, you can pass it as a prop. Then, inside <ExampleComponent /> , you can access the data as this. props. data .

How does setState work in ReactJS?

The setState() schedule changes to the component’s state object and tells React that the component and its children must rerender with the updated state: // Correct this.setState({name: 'Obaseki Nosa'}); React intentionally waits until all components call setState() in their event handlers before rerendering.

How to change the state of a React component?

Whenever the state changes, React re-renders the component to the browser. Before updating the value of the state, we need to build an initial state setup. Once we are done with it, we use the setState () method to change the state object. It ensures that the component has been updated and calls for re-rendering of the component.

How to call setState from a parent component?

You can't directly call setState on a parent component from a child component because the updating of a component state is restricted to the current component.

How do I update the state of a greeting in react?

This object contains the part of the state we want to update which, in this case, is the value of greeting. React takes this value and merges it into the object that needs it. It’s just like the button component asks what it should use for updating the value of greeting and setState () responds with an answer.


2 Answers

If you work with functional components you can use hooks like useState. Don't forget to "save" (memoize) the reference of your handler with useCallback, it helps React avoid useless rerenders.

Functional component solution

// myContainer.js
import React, { useState } from 'react'
import MyChild from 'some/path/myChild'

function MyContainer() {
  const [name, setName] = useState('foo')

  return (
    <MyChild name={name} onNameChange={setName} />
  )
}

export default MyContainer

// myChild.js
import React, { useCallback } from 'react'

function MyChild({ name, onNameChange }) {

  const handleInputChange = useCallback(event => {
    onNameChange(event.target.value)
  }, [onNameChange])

  return (
    <div>
      <input type="text" onChange={handleInputChange} value={name} />
      <div>The name is: {name}</div>
    </div>
  )
}

export default MyChild

In a class you can use handler (method) that contains some logic or function call(s). It help to keep your code maintainable.

Class component solution

// myContainer.js
import React, { Component } from 'react'
import MyChild from 'some/path/myChild'

class MyContainer extends Component {
  state = {
    name: 'foo'
  }

  handleNameChange = name => {
    this.setState({ name })
  }

  render() {
    return (
      <MyChild name={this.state.name} onNameChange={this.handleNameChange} />
    )
  }

}

export default MyContainer

// myChild.js
import React, { Component } from 'react'

class MyChild extends Component {

  handleInputChange = event => {
    this.props.onNameChange(event.target.value)
  }

  render() {
    return (
      <div>
        <input type="text" onChange={this.handleInputChange} value={this.props.name} />
        <div>The name is: {this.props.name}</div>
      </div>
    )
  }

}

export default MyChild
like image 138
Alexandre Nicolas Avatar answered Oct 11 '22 18:10

Alexandre Nicolas


You can't directly call setState on a parent component from a child component because the updating of a component state is restricted to the current component.

To handle this, simply pass a function from the parent to the child that contains setState. So when you want to update the parent's state, just call that passed function.

A minimal example:

// Parent.jsx

import React, { Component } from 'react';
import Child from './Child';

class Parent extends Component {
  constructor(props) {
    super(props);
    this.setChanged = this.setChanged.bind(this);
    this.state = {
      changed: false
    }
  }

  // Function to set the parent's state
  setChanged() {
    this.setState({ changed: true });
  }

  render() {
    return <Child setChanged={this.setChanged} />
  }
}

// Child.js

import React from 'react';

function Child(props) {
  return (
    // When clicked, parent's setChanged function is called
    <div onClick={() => props.setChanged()} />
  )
}
like image 24
Adam Avatar answered Oct 11 '22 19:10

Adam