<body>
<div id="root"></div>
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
<script type="text/babel">
function Greeting() {
// useState - Returns a stateful value, and a function to update it.
// During the initial render, the returned state (state) is the same
// as the value passed as the first argument (initialState).
const [name, setName] = React.useState('');
// The setState function is used to update the state.
// It accepts a new state value and enqueues a re-render of the component.
// During subsequent re-renders, the first value returned by useState
// will always be the most recent state after applying updates.
const handleChange = event => setName(event.target.value);
return (
<div>
<form>
{/* htmlFor is the same thing as For attribute in HTML */}
<label htmlFor="name">Name: </label>
<input onChange={handleChange} id="name" />
</form>
{name ? <strong>Hello {name}</strong> : 'Please type your name'}
</div>
);
}
ReactDOM.render(<Greeting />, document.getElementById('root'));
</script>
</body>
const [name, setName] = React.useState('');
const [name2, setName2] = React.useState('');
const handleChange = event => setName(event.target.value);
const handleChange2 = event => setName(event.target.value);
// ...
<form>
<label htmlFor="name">Name: </label>
<input onChange={handleChange} id="name" />
</form>;
<form>
<label htmlFor="name">Name: </label>
<input onChange={handleChange2} id="name" />
</form>;
// ...