score:4

Accepted answer

is it ok to update react components state by calling its member function from controller?

yes, you can do that but it's unnecessary. usually you want to update the child state by passing down props from the parent. i've made some examples of how you can update a child from the parent below.


example 1:

in this example, you don't need any state for the child. the parent manages the state and passes down any changes to the child via props. this is the recommended approach.

parent

class parent extends react.component {
  constructor() {
    super();
    this.state = {text: "hello"};
  } 

  render() {
    return <child data={this.state.text} />;
  }
}

child

class child extends react.component {    
  render() {
    return <span>{this.props.data}</span>;
  }
}

example 2:

in this example, we use two states, one for each component. this is unnecessary for this implementation, but you can still do it. when the child mounts, we set the state to whatever the data prop is set to. we update the state whenever the child component receives props with componentwillreceiveprops().

parent

class parent extends react.component {
  constructor() {
    super();
    this.state = {text: "hello"};
  } 

  render() {
    return <child data={this.state.text} />;
  }
}

child

class child extends react.component {
  constructor(props) {
    super(props);
    this.state = {childtext: props.data};
  }

  componentwillreceiveprops(nextprops) {
    if(nextprops.data !== this.props.data)
      this.setstate({childtext: data});
  }

  render() {
    return <span>{this.state.childtext}</span>;
  }
}

example 3:

in this example, the child component is given a ref which we then can use to trigger a child function from parent. usually this is done in the reverse order (triggering a function from child to parent), but you can still do this if you want. this is the more manual approach and similar to what you asked.

parent

class parent extends react.component {
  constructor() {
    super();
    this.state = {text: "hello"};
  }

  triggerupdate = () => {
    this.child.component.update(this.state.text);
  }

  render() {
    return <child ref={(el) => this.child = el} data={this.state.text} />;
  }
}

child

class child extends react.component {
  constructor(props) {
    super(props);
    this.state = {childtext: props.data};
  }

  update = (text) => {
    this.state({childtext: text});
  }
    
  render() {
    return <span>{this.state.childtext}</span>;
  }
}

Related Query

More Query from same tag