user3033194 user3033194 - 3 months ago 36
React JSX Question

onChange event not firing for input field with React

I am trying to render a simple input field, in which when the value is changed, a callback from the parent component will be called. My code is given below:

class Parent extends React.Component {
myMethod() {
alert("Test");
}
render() {
return (
<Child cb={this.myMethod} />
);
}
}

class Child extends React.Component {
render() {
return (
<input type="text" placeholder="enter text" onChange="{this.props.cb}" />
);
}
}

Child.propTypes = {
cb: React.PropTypes.func
}

ReactDOM.render(
<Parent />,
document.getElementById("container")
);


My HTML code is:

<div id="container">

</div>


The error I am getting is:

Warning: Failed prop type: Child: prop type `cb` is invalid; it must be a function, usually from React.PropTypes.
in Child (created by Parent)
in Parent

Warning: Failed form propType: Invalid prop `onChange` of type `string` supplied to `input`, expected `function`. Check the render method of `Child`.


I am new to React, and cannot really understand how else I should pass the callback to the Child component. Can someone help please?

Answer

Your onChange prop shouldn't be string:

class Child extends React.Component {
    render() {
        return (
            <input type="text" placeholder="enter text" onChange={this.props.cb} />
        );
    }
}