To have the expected effect and type in the text box and show the result you have to use the useState
to save the current status and in the event onChange
of <input />
change this state, minimum example:
function App() {
const [name, setName] = React.useState('');
return (
<div>
<h1>{name}</h1>
<div>
<input
type="text"
value={name}
onChange={e => setName(e.target.value)}
/>
</div>
</div>
)
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
If you want it to appear from the event onSubmit
of a form, need to involve within a tag
form
the elements and make a reference to tag <h1>
with useRef()
and from the submission of the rescue form the value of the state variable and send by reference to the h1
, example:
function App() {
const [name, setName] = React.useState('');
const refH1 = React.useRef();
const handleSubmit = (e) => {
e.preventDefault();
refH1.current.innerHTML = name;
}
return (
<div>
<h1 ref={refH1}></h1>
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={e => setName(e.target.value)}
/>
<button>Enviar</button>
</form>
</div>
</div>
)
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Have you ever consulted Documentation about React forms? She’s not wearing it yet Hooks, but as you said already know how they work, can give an idea of how it works.
– Luiz Felipe
Several examples, one of them: https://answall.com/questions/463410/problema-na-l%C3%b3gica-React-n%C3%a3o-calcula/463417#463417
– novic
Another example: https://answall.com/questions/426304/duvida-sobre-padr%C3%a3o-classe-React/426335#426335
– novic
This answers your question? onChange on React not working!
– novic
Another example: https://answall.com/questions/476269/onchange-em-react-n%C3%a3o-working/476273#476273
– novic