Reputation: 14926
I am experimenting with passing event handlers to parent components so I wrote this code:
import React, { useState } from "react";
export default function App() {
const [val, setVal] = useState("");
function handleChange(event) {
console.log(event.target);
setVal(event.target.value);
}
return (
<div className="App">
<TextInput onChange={handleChange} />
<div>{val}</div>
</div>
);
}
function TextInput(props) {
return <input onChange={props.handleChange} type="text" />;
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
(I don't know why stackoverflow cant handle export in above code, how do I make that work? Here is codesandbox - https://codesandbox.io/s/onchange-test-1pxdr?file=/src/index.js)
I would expect when typing in box the text under the box should update but nothing happens and no error. Why is this?
Upvotes: 1
Views: 1529
Reputation: 968
The error that you did is pretty simple. The rule of passing props is that you cannot access it in the child component by the same name you have given to the function in parent component.
Your function name:
function handleChange(event)
Access it by the name you have passed in as props which is onChange
and not handleChange
in this case:
<TextInput onChange={handleChange} />
You can use two ways at the child component props.onChange
:
<input onChange={props.onChange} type="text" />
or by using props destructuring:
function TextInput({onChange}) {
<input onChange={onChange} type="text" />
}
Upvotes: 2
Reputation: 6766
It should be onChange={props.onChange}
function TextInput(props) {
return <input onChange={props.onChange} type="text" />;
}
Upvotes: 1