I am working in Reactjs and using Nextjs,I am facing problem with "text box",whenever i use "value" in textbox then i cant type anything in "textbox" and if i use "defaultvalue" in "textbox" then i am getting validation message "Please enter your email" How can i fix this ? Here is my code
<input
type="text"
name="email"
id="email"
placeholder="Type your email here"
value={state.name}
onChange={handleChange2}
/>
And here if nextjs code
const value = e.target.value;
setState({
...state,
[e.target.email]: value
});
};
const handleSubscribe = (e) => {
e.preventDefault();
if (state.email == '') {
//showing error message
} else {
//further code
}
};
CodePudding user response:
This could work, minimal example to reproduce
input prop
name => name="email"
// set state with [e.target.name]
setValue({ ...value, [e.target.name]: e.target.value })
const [value, setValue] = React.useState({})
return (
<input
name="email"
value={value.email}
onChange={(e) =>setValue({ ...value, [e.target.name]: e.target.value })}
/>
);
Basic explanation of event handlers
const SomeComponent = (props) => {
// will be created for every render, but looks cleaner
// this can be wrapped with useCallback if needed for optimization
const onTextChange = (event) => {
// event handling code
}
return (
... other render code
<input onChange={onTextChange} />
...
<input onChange={(event) => {
// in line event handler
// will be re created for every render
}} />
)
}
React new documenation on event handling will give you idea of standard practices
Hope it helps
CodePudding user response:
Simply do this:
const [value, setValue] = useState({});
const handleOnChange = (event) => {
setValue({...value, [event.target.name]: event.target.value});
}
return (
<form onSubmit={handleSubscribe}>
<input
name="email"
value={value.email}
onChange={handleOnChange}
/>
<button>Send</button>
</form>
);