1

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?

2 Answers 2

3

Your onChange prop shouldn't be string:

class Child extends React.Component {
    render() {
        return (
            <input type="text" placeholder="enter text" onChange={this.props.cb} />
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Remove the quotation marks around the value of onChange:

<input type="text" placeholder="enter text" onChange={this.props.cb} />

1 Comment

Thanks a lot for the reply!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.