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?
Answer
It should be onChange={props.onChange}
function TextInput(props) { return <input onChange={props.onChange} type="text" />; }