Ad

How To Trigger A Child Component Event In ComponentDidMount

- 1 answer

Given the following, how do I trigger an event for the Foo component in componentDidMount:

import React, {Component} from 'react';
import Foo from 'Foo';

export default class Bar extends Component {

  componentDidMount() {
    // How to trigger the onChange event for this.refs.foo
  }

  render() {

    const onFooChanged= (resultFromFoo) => {
        // do stuff
    };

    return (
      <div>
        <Foo ref="foo" onChange={onFooChanged} />
      </div>
    );
  }
}
Ad

Answer

If you inject the onChange function as a prop, you simply can access the prop and call it.

componentDidMount() {
    this.refs.foo.props.onChange()
  }

I added a fiddle: https://jsfiddle.net/69z2wepo/27193/

Ad
source: stackoverflow.com
Ad