I'm struggling with a simple task in React I have an input field that accepts a string or number. When pressing the reset button, the value of the input field should go blank so I can add a new string. I've made it possible to clear the form but when it's cleared, I can't type something else. Is it because I'm using state? Any solutions?
my code:
import React from 'react';
import './Input.css';
import { useState } from 'react';
const Input = () => {
const [value, setValue] = useState();
const SearchButton = (e) => {
e.preventDefault();
console.log("click");
};
const ResetButton = (e) => {
e.preventDefault();
setValue(" ");
};
return (
<main>
<form className='inputfield'>
<h2 className='input-text'>Zoek een Github user</h2>
<div className='input'>
<input className='search' type='text' placeholder='Typ hier een gebruikersnaam...' value={value}></input>
<div className='button-field'>
<button className='search-now' onClick={SearchButton}>Zoeken</button>
<button className='reset' onClick={ResetButton}>Reset</button>
</div>
</div>
</form>
</main>
);
};
export default Input;
CodePudding user response:
You should have an onChange
function in your inputs.
<input onChange={(e) => setValue(e.target.value)}></input>
CodePudding user response:
You forgot to update state when changing the value. For example:
<input
className='search'
type='text'
placeholder='Typ hier een gebruikersnaam...'
value={value}
onChange={e => setValue(e.target.value)}
></input>
Basically what's happening is that when your component first loads you aren't using state, so the input
is "uncontrolled" because value
is undefined
. Then the "reset" sets a value to the state, so the input
now uses that value. But it needs a way to change that value.
As an aside, I also recommend using an empty string as the initial state, instead of undefined
:
const [value, setValue] = useState("");
That way the value is at least something, even if it's empty. You might also want the "reset" to use an empty string instead of a space:
setValue("");
Because a space is a non-empty value, and it causes the placeholder text to no longer show. So it isn't really "resetting" the input, it's just changing it to a whitespace value.
CodePudding user response:
en primer lugar, debe cambiar el valor setValue y debería verse así
const [value, setValue] = useState('');
and secondly you need to add this to the input
<input onChange={(e) => setValue(e.target.value)}></input>