I have a React application and in it I have an input field. I work with Bootstrap. When the user clicks a button, I want the input field to be filled automatically. So at the beginning it should be empty, because the variable name = ""
and as soon as the button is pressed the name Max
should be in the input field, how do I do that?
My Code
const Profile = () => {
const [name, setName] = useState();
const onClickBack = () => {
setName('Max');
}
return (
<div>
<div className="form-group">
<div className="col-xs-4">
<label for="exampleInputName">Name</label>
<input
type="text"
className={name ? "form-control" : "form-control is-invalid"
}
placeholder={name}
onChange={(event) =>
setValueName(event.target.value)
}
// text = {name} // not working
/>
</div>
</div>
<button
type="button"
id="submit"
name="submit"
className="btn btn-primary submit-button ml-5"
onClick={onClickBack}
>
Back
</button>
</div>
);
};
export default Profile;
It's quite simple. Use value={name}
instead of text={name}
<input
type="text"
className={name ? "form-control" : "form-control is-invalid"}
placeholder={name}
value={name}
onChange={(event) =>
setValueName(event.target.value)
}
/>