How can i put value in input? - reactjs

Why can't I put a value in the input? The problem is: I need to put a 'name' in <Form.Item> to apply the rules. Without that, the rules will not be able to work, but if you remove the name="userName" from <Form.Item the value appears at the input.
How can i solve that?
<Form autoComplete="off" layout="vertical" onFinish={handleFinish}>
<Form.Item name="userName" rules={getTextRule('name')}>
<Input value={fields?.firstName} name="firstName" onChange={(e) => {
handleInputChange(e)
}} />
</Form.Item>
</Form.Item>

simple we can code like
const [text,setText] = useState('')
return(
<input type='text' value={text} onChange={e=>setText(e.target.value)}/>
)

If you use the form you can let Ant Form manage the state by removing the value & the onChange props on the <Input />.
Else if you manage the state by yourself make sure to get the value from the e.target.value.
ex:
const [fields, setFields] = useState({})
const handleOnChange = (e) => {
setFields((state) => {
...state,
[e.target.name]: e.target.value,
})
}
return (
<Input
name="firstName"
value={fields.firstName}
onChange={handleOnChange}
/>
)

Related

Set state for incremental numbers input

After months without reactjs I forgot how to solve this situation. I have a incremental input for numbers:
HTML:
<input
type="number"
value={stockQuantity}
defaultValue="1"
onChange={() => bookQuantity(stockQuantity)}
/>
React
const [stockQuantity, setStockQuantity] = useState(1);
const bookQuantity = (e) => {
setStockQuantity({ ...stockQuantity, [e.target.name]: e.target.value });
};
I just get errors I don't find the solution and I didn't find any previous work were I handle it.
Any idea?
You should define stockQuantity as an object initially:
const [stockQuantity, setStockQuantity] = useState({books: 1});
Then you can just setState in onChange event or create a separate function as you have already made.
You don't have to set the value prop
<input
type="number"
name="books"
defaultValue="1"
onChange={(e) => setStockQuantity({...stockQuantity, [e.target.name]: e.target.value})}
/>
You need to pass the event to your onChange handler and also add name to your input:
<input
type="number"
name="stockQuantity" // will be passed in e.target.name
value={stockQuantity}
defaultValue="1"
onChange={bookQuantity} // the same as onChange={(e) => bookQuantity(e)}
/>
I have found a little linear solution:
const [stockQuantity, setStockQuantity] = useState(1); // just numbers
const bookQuantity = (e) => {
setStockQuantity({ ...stockQuantity, [e.target.name]:
e.target.value });
};
HTML:
<input
type="number"
name="stock"
value={stockQuantity.books}
defaultValue="1"
onChange={bookQuantity}
// if you want you can use a placeholder
/>

React Boostrap input form doesn't give any value

Hi everybody Tring to make a form with Form provided by bootstap but it doesn't work.
If I insert value it doesn't let me type, without value I digit but I can't get the value.
(I have also a Gatsby theme activated)
const StandAdd = () => {
const [item, setItem] = useState({
title: "",
kindof: "",
website: "",
image01: "",
image02: "",
image03: "",
})
const { title, kindof, website, image01, image02, image03 } = item
const handleInputChange = event => {
event.preventDefault()
setItem({ ...item, [event.target.name]: event.target.value })
}
const handleSubmit = event => {
event.preventDefault()
alert(`${title} ${item} ${website}`) // always empty I gat get anything
}
return (
<Layout>
<form onSubmit={handleSubmit}>
<Form>
<Form.Group controlId="title">
{/* <Form.Label>Email address</Form.Label> */}
<Form.Control
value={titlet} // <-- this blocks the typing
type="text"
placeholder="Enter Stand's Name"
onChange={handleInputChange}
/>
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</form>
</Layout>
)
}
export default StandAdd
Any idea?
The issue is here:
<Form.Control
value="title" // <-- this blocks the typing
type="text"
placeholder="Enter Stand's Name"
onChange={handleInputChange}
/>
here you have to provide the name attribute so that your code:
setItem({ ...item, [event.target.name]: event.target.value })
will get some value in event.target.name.
So after adding name the code will be like:
<Form.Control
type="text"
name="title" <---- name added here
placeholder="Enter Stand's Name"
onChange={handleInputChange}
/>
And don't provide a hard-coded value to input like this:
value="title"
instead use defaultValue for providing an initial value.
I think you need to provide name attribute to <Form.Control> component.

Unable to change Formik forms text field

I am using the following code:
<Formik initialValues={{val:cell.value}}>
<Form>
<Field type="text" name="val" size="2" onChange = {(e)=> {console.log(e.target)}}></Field>
</Form>
</Formik>
and I am unable to change the value at UI. What am I doing wrong?
Formik should be handling the changes. See the following example: https://jaredpalmer.com/formik/docs/api/formik
Note that the input in the example is triggering Formik's handleChange in the onChange:
onChange={props.handleChange}
App.js
I used functional component and useState.
const App = () => {
const cell = { value: "test" };
const [myVal, setMyVal] = useState(cell.value);
return (
<div>
<Formik initialValues={{ val: cell.value }}>
<Form>
<Field
type="text"
name="val"
size="20"
placeholder="type something"
value={myVal}
onChange={e => {
console.log(e.target.value);
setMyVal(e.target.value);
}}
/>
</Form>
</Formik>
</div>
);
};
check out the demo code
In your onChange, you need to update the state, which then gets passed back into Formik. Right now you are just outputting the value.

Getting uncontrolled input error even though everything is controlled

I need your help, I'm trying to use a form from react-strap and for some reason I get this error:
Warning: A component is changing a controlled input of type password to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component
this is my code.
everything is controlled but I still get the error, can anyone spot my mistake?
const LoginForm = () => {
const [formData, setFormData] = useState({
email: " ",
password: " "
});
const onChange = e => {
setFormData({
[e.target.name]: e.target.value
});
};
const onSubmit = e => {
e.preventDefault();
console.log("email password are", formData.email, formData.password);
loginUser(formData.email, formData.password);
};
return (
<Form onSubmit={onSubmit}>
<FormGroup>
<h1>Login</h1>
</FormGroup>
<FormGroup>
<Label for="Email">Email</Label>
<Input
type="email"
name="email"
id="Email"
placeholder="example#mail.com"
onChange={onChange}
value={formData.email}
/>
</FormGroup>
<FormGroup>
<Label for="Password">Password</Label>
<Input
type="password"
name="password"
id="Password"
placeholder="password"
onChange={onChange}
value={formData.password}
/>
</FormGroup>
<Button>Submit</Button>
</Form>
);
};
Ok I found the error, I didn't spread the last answer, so by inputting password I overwritten my email, the proper on change should be this:
const onChange = e => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};

React - this.input.value vs handle change

What is better?
I have a form with 10 inputs.
Should I use this.input.value or handle change and store it in state?
handleChange(e) {
this.setState({input: e.target.value});
}
...
<input type="text" value={this.state.input} onChange={this.handleChange} />
or
onSubmit() {
const inputValue = this.input.value;
...
}
...
<input type="text" ref={(input) => {this.input = input;}} />
From the documentation:
When to Use Refs
There are a few good use cases for refs:
Managing focus, text selection, or media playback.
Triggering imperative animations.
Integrating with third-party DOM libraries.
Avoid using refs for anything that can be done declaratively.
Setting up controlled inputs is kind of a pain, but I use this pattern to make it a little easier.
Create one onChange event handler for ALL inputs:
handleInputChange(e){
const target = e.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
Then, for your inputs, be sure to give it a name that matches a key in your state to update.
render() {
const { firstName, lastName, email, acceptTerms } = this.state;
return (
<form>
<input name="firstName" onChange={this.handleInputChange} value={firstName} />
<input name="lastName" onChange={this.handleInputChange} value={lastName} />
<input name="email" onChange={this.handleInputChange} value={email} />
<input type="checkbox" name="acceptTerms" onChange={this.handleInputChange} checked={acceptTerms} />
</form>
)
}

Resources