I am using React JS.
I am setting the state, however, there is a problem, in the value={} part of the input field.
Here is my code:
import React from 'react';
class SomeClass extends React.Component{
constructor(props){
super(props);
this.state = {
passCode: {
email: "Email",
password: "Password"
},
errorMessage: ''
};
}
handleChange = (event) =>{
console.log(`input detected`);
let request = Object.assign({},this.state.passCode);
request.email = event.target.value;
request.password = event.target.value;
this.setState({passCode: request});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>Email Address</label>
<input type="text" value={this.state.passCode.email} onChange={this.handleChange} placeholder="Enter Email Address" />
<label>Password</label>
<input type="password" value={this.state.passCode.password} onChange={this.handleChange} placeholder="Enter One Time Password" />
<Button type="submit">
Sign In</Button>
</form>
);
}
}
export default SomeClass;
My Question:
I have is for the value attribute of the input fields, I think setState is not working properly:
In the passCode object of the state.
When I type the email, both fields get set to what I typed in the email field.
When I type the password, both fields get set to what I typed in the password field.
What's the reason for such problem?
setState is working properly; your handleChange isn't. You're setting both email and password to the value of the input regardless of which input the change occurred on. Instead, you want to update just the relevant property. To do that, I'd add name attributes to the input elements (name="email" and name="password"), then:
handleChange = ({currentTarget: {name, value}}) =>{
console.log(`input detected`);
this.setState(({passCode}) => {
return {passCode: {...passCode, [name]: value}};
});
};
Key bits there are:
It only updates the property the change related to, keeping the other one unchanged, by using the name of the input.
It uses the callback version of setState (best practice since we're setting state based on existing state).
Your funtion handleChange is wrong. You should update like this with using name:
handleChange = (event) => {
console.log(`input detected`);
const { name, value } = event.target;
this.setState({ passCode: { ...this.state.passCode, [name]: value } });
};
And set name to input:
<input type="text" value={this.state.passCode.email} onChange={this.handleChange} placeholder="Enter Email Address" name="email" />
<input type="password" value={this.state.passCode.password} onChange={this.handleChange} placeholder="Enter One Time Password" name="password" />
The methods they gaved are good, but I still suggest that you separate the methods of changing the two, maybe it will be much better.
I am new to reactjs I want to add onchange in my application. I am using map function for data.
onChange = (event,k,i) => {
this.setState({
dList: update(this.state.dList[k][i], {
[event.target.name]:
{$set: event.target.value}
})
})
}
state example
state = {
name:'',
password:''
}
Incase you have multiple inputs of example name and password
<input type="text" name="name" value={name} onChange={this.handleChange} />
<input type="password" name="password" value={password} onChange={this.handleChange} />
this how you apply the onchange handler
handleChange = e => {
this.setState({[e.target.name]: e.target.value})
}
You should put an onChange function in a onChange html tag attribute.
Example:
<input type="text" value={this.state.value} onChange={this.handleChange} />
Reference
If you want to update your component's state which depends on the previous state of the component, use the overloaded version of setState which takes a function as a parameter. This is because the calls made to the setState function are batched to improve performance.
onChange = (event,k,i) => {
this.setState(prevState => {
dList: update(prevState.dList[k][i], {
[event.target.name]:
{$set: event.target.value}
})
})
}
Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.*
Following is my code:
constructor(props) {
super(props);
this.state = {
fields: {},
errors: {}
}
this.onSubmit = this.onSubmit.bind(this);
}
....
onChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
....
render() {
return(
<div className="form-group">
<input
value={this.state.fields["name"]}
onChange={this.onChange.bind(this, "name")}
className="form-control"
type="text"
refs="name"
placeholder="Name *"
/>
<span style={{color: "red"}}>{this.state.errors["name"]}</span>
</div>
)
}
The reason is, in state you defined:
this.state = { fields: {} }
fields as a blank object, so during the first rendering this.state.fields.name will be undefined, and the input field will get its value as:
value={undefined}
Because of that, the input field will become uncontrolled.
Once you enter any value in input, fields in state gets changed to:
this.state = { fields: {name: 'xyz'} }
And at that time the input field gets converted into a controlled component; that's why you are getting the error:
A component is changing an uncontrolled input of type text to be
controlled.
Possible Solutions:
1- Define the fields in state as:
this.state = { fields: {name: ''} }
2- Or define the value property by using Short-circuit evaluation like this:
value={this.state.fields.name || ''} // (undefined || '') = ''
Changing value to defaultValue will resolve it.
Note:
defaultValue is only for the initial load.
If you want to initialize the input then you should use defaultValue, but if you want to use state to change the value then you need to use value. Read this for more.
I used value={this.state.input ||""} in input to get rid of that warning.
Inside the component put the input box in the following way.
<input className="class-name"
type= "text"
id="id-123"
value={ this.state.value || "" }
name="field-name"
placeholder="Enter Name"
/>
In addition to the accepted answer, if you're using an input of type checkbox or radio, I've found I need to null/undefined check the checked attribute as well.
<input
id={myId}
name={myName}
type="checkbox" // or "radio"
value={myStateValue || ''}
checked={someBoolean ? someBoolean : false}
/>
And if you're using TS (or Babel), you could use nullish coalescing instead of the logical OR operator:
value={myStateValue ?? ''}
checked={someBoolean ?? false}
SIMPLY, You must set initial state first
If you don't set initial state react will treat that as an uncontrolled component
that's happen because the value can not be undefined or null to resolve you can do it like this
value={ this.state.value ?? "" }
const [name, setName] = useState()
generates error as soon as you type in the text field
const [name, setName] = useState('') // <-- by putting in quotes
will fix the issue on this string example.
As mentioned above you need to set the initial state, in my case I forgot to add ' ' quotes inside setSate();
const AddUser = (props) => {
const [enteredUsername, setEnteredUsername] = useState()
const [enteredAge, setEnteredAge] = useState()
Gives the following error
Correct code is to simply set the initial state to an empty string ' '
const AddUser = (props) => {
const [enteredUsername, setEnteredUsername] = useState('')
const [enteredAge, setEnteredAge] = useState('')
Set Current State first ...this.state
Its because when you are going to assign a new state it may be undefined. so it will be fixed by setting state extracting current state also
this.setState({...this.state, field})
If there is an object in your state, you should set state as follows,
suppose you have to set username inside the user object.
this.setState({user:{...this.state.user, ['username']: username}})
Best way to fix this is to set the initial state to ''.
constructor(props) {
super(props)
this.state = {
fields: {
first_name: ''
}
}
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.setState({
fields:{
...this.state.fields,
[e.target.name]: e.target.value
}
})
}
render() {
return(
<div className="form-group">
<input
value={this.state.fields.first_name}
onChange={this.onChange}
className="form-control"
name="first_name" // Same as state key
type="text"
refs="name"
placeholder="Name *"
/>
<span style={{color: "red"}}>{this.state.errors.first_name}</span>
</div>
)
}
Then you can still run your checks like if (field) and still achieve the same result if you have the value as ''.
Now since your value is now classified as type string instead of undefined after evaluation. Thus, clearing the error from the console of a big red block 😁😎.
I am new to reactjs and I am using version 17 of reactjs
I was getting this problem
I solved:
Instead of this
const [email, setEmail] = useState();
I added this
const [email, setEmail] = useState("");
In useState function I added quotes to initialize the data and the error was gone.
Put empty value if the value does not exist or null.
value={ this.state.value || "" }
If you're setting the value attribute to an object's property and want to be sure the property is not undefined, then you can combine the nullish coalescing operator ?? with an optional chaining operator ?. as follows:
<input
value={myObject?.property ?? ''}
/>
In my case it was pretty much what Mayank Shukla's top answer says. The only detail was that my state was lacking completely the property I was defining.
For example, if you have this state:
state = {
"a" : "A",
"b" : "B",
}
If you're expanding your code, you might want to add a new prop so, someplace else in your code you might create a new property c whose value is not only undefined on the component's state but the property itself is undefined.
To solve this just make sure to add c into your state and give it a proper initial value.
e.g.,
state = {
"a" : "A",
"b" : "B",
"c" : "C", // added and initialized property!
}
Hope I was able to explain my edge case.
If you use multiple input in on field, follow:
For example:
class AddUser extends React.Component {
constructor(props){
super(props);
this.state = {
fields: { UserName: '', Password: '' }
};
}
onChangeField = event => {
let name = event.target.name;
let value = event.target.value;
this.setState(prevState => {
prevState.fields[name] = value;
return {
fields: prevState.fields
};
});
};
render() {
const { UserName, Password } = this.state.fields;
return (
<form>
<div>
<label htmlFor="UserName">UserName</label>
<input type="text"
id='UserName'
name='UserName'
value={UserName}
onChange={this.onChangeField}/>
</div>
<div>
<label htmlFor="Password">Password</label>
<input type="password"
id='Password'
name='Password'
value={Password}
onChange={this.onChangeField}/>
</div>
</form>
);
}
}
Search your problem at:
onChangeField = event => {
let name = event.target.name;
let value = event.target.value;
this.setState(prevState => {
prevState.fields[name] = value;
return {
fields: prevState.fields
};
});
};
Using React Hooks also don't forget to set the initial value.
I was using <input type='datetime-local' value={eventStart} /> and initial eventStart was like
const [eventStart, setEventStart] = useState();
instead
const [eventStart, setEventStart] = useState('');.
The empty string in parentheses is difference.
Also, if you reset form after submit like i do, again you need to set it to empty string, not just to empty parentheses.
This is just my small contribution to this topic, maybe it will help someone.
like this
value={this.state.fields && this.state.fields["name"] || ''}
work for me.
But I set initial state like this:
this.state = {
fields: [],
}
I came across the same warning using react hooks,
Although I had already initialized the initial state before as:-
const [post,setPost] = useState({title:"",body:""})
But later I was overriding a part of the predefined state object on the onChange event handler,
const onChange=(e)=>{
setPost({[e.target.name]:e.target.value})
}
Solution
I solved this by coping first the whole object of the previous state(by using spread operators) then editing on top of it,
const onChange=(e)=>{
setPost({...post,[e.target.name]:e.target.value})
}
Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
Solution : Check if value is not undefined
React / Formik / Bootstrap / TypeScript
example :
{ values?.purchaseObligation.remainingYear ?
<Input
tag={Field}
name="purchaseObligation.remainingYear"
type="text"
component="input"
/> : null
}
The reason of this problem when input field value is undefined then throw the warning from react. If you create one changeHandler for multiple input field and you want to change state with changeHandler then you need to assign previous value using by spread operator. As like my code here.
constructor(props){
super(props)
this.state = {
user:{
email:'',
password:''
}
}
}
// This handler work for every input field
changeHandler = event=>{
// Dynamically Update State when change input value
this.setState({
user:{
...this.state.user,
[event.target.name]:event.target.value
}
})
}
submitHandler = event=>{
event.preventDefault()
// Your Code Here...
}
render(){
return (
<div className="mt-5">
<form onSubmit={this.submitHandler}>
<input type="text" value={this.state.user.email} name="email" onChage={this.changeHandler} />
<input type="password" value={this.state.user.password} name="password" onChage={this.changeHandler} />
<button type="submit">Login</button>
</form>
</div>
)
}
Multiple Approch can be applied:
Class Based Approch: use local state and define existing field with default value:
constructor(props) {
super(props);
this.state = {
value:''
}
}
<input type='text'
name='firstName'
value={this.state.value}
className="col-12"
onChange={this.onChange}
placeholder='Enter First name' />
Using Hooks React > 16.8 in functional style components:
[value, setValue] = useState('');
<input type='text'
name='firstName'
value={value}
className="col-12"
onChange={this.onChange}
placeholder='Enter First name' />
If Using propTypes and providing Default Value for propTypes in case of HOC component in functional style.
HOC.propTypes = {
value : PropTypes.string
}
HOC.efaultProps = {
value: ''
}
function HOC (){
return (<input type='text'
name='firstName'
value={this.props.value}
className="col-12"
onChange={this.onChange}
placeholder='Enter First name' />)
}
Change this
const [values, setValues] = useState({intialStateValues});
for this
const [values, setValues] = useState(intialStateValues);
I also faced the same issue. The solution in my case was I missed adding 'name' attribute to the element.
<div className="col-12">
<label htmlFor="username" className="form-label">Username</label>
<div className="input-group has-validation">
<span className="input-group-text">#</span>
<input
type="text"
className="form-control"
id="username"
placeholder="Username"
required=""
value={values.username}
onChange={handleChange}
/>
<div className="invalid-feedback">
Your username is required.
</div>
</div>
</div>
After I introduced name = username in the input list of attributes it worked fine.
For functional component:
const SignIn = () => {
const [formData, setFormData] = useState({
email: "",
password: ""
});
const handleChange = (event) => {
const { value, name } = event.target;
setFormData({...formData, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log("Signed in");
setFormData({
email: "",
password: ""
});
};
return (
<div className="sign-in-container">
<form onSubmit={handleSubmit}>
<FormInput
name="email"
type="email"
value={formData.email}
handleChange={handleChange}
label="email"
required
/>
<FormInput
name="password"
type="password"
value={formData.password}
handleChange={handleChange}
label="password"
required
/>
<CustomButton type="submit">Sign in</CustomButton>
</form>
</div>
);
};
export default SignIn;
While this might sound crazy, the thing that fixed this issue for me was to add an extra div. A portion of the code as an example:
... [Other code] ...
const [brokerLink, setBrokerLink] = useState('');
... [Other code] ...
return (
... [Other code] ...
<div styleName="advanced-form" style={{ margin: '0 auto', }}>
{/* NOTE: This div */}
<div>
<div styleName="form-field">
<div>Broker Link</div>
<input
type="text"
name="brokerLink"
value={brokerLink}
placeholder=""
onChange={e => setBrokerLink(e.target.value)}
/>
</div>
</div>
</div>
... [Other code] ...
);
... [Other code] ...
Was very strange. Without this extra div, it seems react initially rendered the input element with no value attribute but with an empty style attribute for some reason. You could see that by looking at the html. And this led to the console warning..
What was even weirder was that adding a default value that is not an empty string or doing something like value={brokerLink || ''} would result in the exact same problem..
Another weird thing was I had 30 other elements that were almost exactly the same but did not cause this problem. Only difference was this brokerLink one did not have that outer div..
And moving it to other parts of the code without changing anything removed the warning for some reason..
Probably close to impossible to replicate without my exact code. If this is not a bug in react or something, I don't know what is.
The problem occurs even if you set undefined to the value at a previous rendering that happened even before initializing things properly.
The issue went by replacing
value={value}
with
value={(value==undefined?null:value)}
For me, this was the mistake:
<input onChange={onClickUpdateAnswer} value={answer.text}>
{answer.text}
</input>
As you see, I have passes string into the body of the Input tag,
Fix:
<input onChange={onClickUpdateAnswer} value={answer.text}></input>
I have a react based form with more than 10 fields in it, I have states for those ten form fields (controlled component).
Most of these input fields are of type text only but other types fields will be added later.
Problem is that I need to write 10 change handlers for them to set state correctly and then add method bindings for each of them in constructor.
I am quite new to react and may be not aware about correct
methodologies and techniques.
Please guide me to how to improve my current code structure and avoid writing boiler plates and repetitive error prone code.
My current Registration component is like below -
export default class Register extends Component {
constructor(props){
super(props);
this.state = {
regName : '',
regAdd1 : '',
regAdd2 : '',
regState : '',
regZipCode : '',
regCity : '',
regPhone : ''
};
// add bindings .... ugh..
this.changeRegAdd1 = this.changeRegAdd1.bind(this);
this.changeRegAdd2 = this.changeRegAdd2.bind(this);
//Similary binding for other handlers...
}
// add individual field change handlers ... ugh...
changeRegName(e) {
this.setState({regName:e.target.value});
}
changeRegAdd1(e) {
this.setState({regAdd1:e.target.value});
}
changeRegAdd2(e) {
this.setState({regAdd2:e.target.value});
}
changeRegState(e) {
this.setState({regState:e.target.value});
}
// Similary for other change handler ....
handleSubmit(e) {
e.preventDefault();
// validate then do other stuff
}
render(){
let registrationComp = (
<div className="row">
<div className="col-md-12">
<h3>Registration Form</h3>
<fieldset>
<div className="form-group">
<div className="col-xs-12">
<label htmlFor="regName">Name</label>
<input type="text" placeholder="Name"
onChange={this.changeregName} value = {this.state.regName} className="form-control" required autofocus/>
</div>
</div>
<div className="form-group">
<div className="col-xs-12">
<label htmlFor="regAdd1">Address Line1</label>
<input
type = "text"
placeholder = "Address Line1"
onChange = {this.changeregAdd1}
value = {this.state.regAdd1}
className = "form-control"
required
autofocus
/>
<input
type = "text"
placeholder = "Address Line2"
onChange = {this.changeregAdd2}
value = {this.state.regAdd2}
className = "form-control"
required
autofocus
/>
</div>
</div>
<div className="form-group">
<div className="col-xs-6">
<label htmlFor="regState">State</label>
<input
type = "text"
placeholder = "State"
onChange = {this.changeregState}
value = {this.state.regState}
className = "form-control"
required
autofocus
/>
</div>
<div className="col-xs-6">
<label htmlFor="regZipCode">Zip Code</label>
<input
type = "text"
placeholder = "Zip Code"
onChange = {this.changeregZipCode}
value = {this.state.regZipCode}
className = "form-control"
required
autofocus
/>
</div>
</div>
<div className="form-group">
<div className="col-xs-12">
<label htmlFor="regCity">City</label>
<input
type = "text"
placeholder = "City"
title = "City"
onChange = {this.changeregCity}
value = {this.state.regCity}
className = "form-control"
required
autofocus
/>
</div>
</div>
{/* other form fields */}
</fieldset>
</div>
</div>
);
return registrationComp;
}
}
There can be other lots of ways to do it which I may not be aware.
But I prefer to do change handling in a common method for certain type of common fields such as <input type of text />
This is a sample input field -
<input
onChange = {this.onChange}
value = {this.state.firstName}
type = "text"
name = {"firstName"}
/>
I keep both state's field name and input's "name" attribute same.
After that I write a common change handler for all such fields.
Need to write just one line in change handler.
onChange(e) {
this.setState({[e.target.name]: e.target.value});
}
I am using es6's dynamic property setting from string as property name
{ ["propName] : propValue }.
To avoid writing manual binding for methods in react component you can follow below two approaches -
Use es6 arrow functions
A hack ( I don't know whether this approach is fast or slow but It works :) )
create a method like this in your component.
_bind(...methods) {
methods.forEach( (method) => this[method] = this[method].bind(this) );
}
use _bind to bind your methods.
constructor(props){
super(props);
this.state = {
regName : '',
regAdd1 : '',
regAdd2 : '',
regState : '',
regZipCode : '',
regCity : '',
regPhone : ''
};
// add bindings .... ugh..
//this.changeRegAdd1 = this.changeRegAdd1.bind(this);
//this.changeRegAdd2 = this.changeRegAdd2.bind(this);
//Similary binding for other handlers...
this._bind(
'changeRegName',
'changeReg1' , 'changeRegAdd2'
// and so on.
);
}
EDIT :
Adding validation -
Write a method which can iterate over state keys and check if state is empty.
If any of the input field is empty collect the detail about that input and mark that required.
set a state to indicate that form has errors. Specific error details can be found in state's error object.
validateInput() {
let errors = {};
Object.keys(this.state)
.forEach((stateKey) => {
isEmpty(this.state[stateKey]) ? (errors[stateKey] = `*required` ) : null;
});
return {
errors,
isValid : isEmptyObj(errors)
};
}
isFormValid() {
const { errors, isValid } = this.validateInput();
if (!isValid) {
this.setState({ errors});
}
return isValid;
}
onSubmit(e) {
e.preventDefault();
this.setState({errors : {}});
if (this.isFormValid()) {
// Perform form submission
}
}
I have used to utility method calld isEmpty, isEmptyObj. They just check if object is null or undefined or field is empty.
I hope this helps.
You could create a higher order component to handle a lot of that for you. Redux Form has a pretty good pattern you could model it after if you wanted.
You would essentially end up with something like the following (I have not tested this at all, but it should work pretty well):
export class Field extends Component {
handleChange = (event) => this.props.onChange(this.props.name, event.target.value)
render() {
const InputComponent = this.props.component
const value = this.props.value || ''
return (
<InputComponent
{...this.props}
onChange={this.handleChange}
value={value}
/>
}
}
export default function createForm(WrappedComponent) {
class Form extends Component {
constructor() {
super()
this.state = this.props.initialValues || {}
this.handleChange = this.handleChange.bind(this)
}
handleChange(name, value) {
this.setState({
[name]: value,
})
}
render() {
return (
<WrappedComponent
{...this.state}
{...this.props}
// pass anything you want to add here
onChange={this.handleChange}
values={this.state}
/>
)
}
}
return Form
}
Then you can augment this one component as necessary (add focus, blur, submit handlers, etc). You would use it something like this:
import createForm, { Field } from './createForm'
// simplified Registration component
export class Registration extends Component {
render() {
return (
<form>
<Field
component="input"
name="name"
onChange={this.props.onChange}
type="text"
value={this.props.values.name}
/>
</form>
)
}
}
export default createForm(Registration)
You could go crazy and get into context so you don't have to manually pass values and function around, but I would stay away at least until you're more familiar with React.
Also, if you don't want to manually bind functions, you could use the class properties transform if you're using babel. Then the Form component would just look like the following:
class Form extends Component {
state = this.props.initialValues || {}
handleChange = (name, value) => this.setState({
[name]: value,
})
render() {
return (
<WrappedComponent
{...this.state}
{...this.props}
onChange={this.handleChange}
values={this.state}
/>
)
}
}
Take a look at how it's done in NeoForm:
data state is directly mapped to form fields
one onChange handler for the entire form
per-field (for example onBlur) and form (for example onSubmit) validation
plain object and Immutable state helpers
easy integration with Redux or any other state management solution
It uses context internally and really small and modular source code is easy to follow.
I see that an onChange listener usually doesn't have extra arguments other than e.
handleOnChange(e) {
this.setState({email: e.target.value});
}
But is it still possible to pass extra arguments? Like this:
handleOnChange(e,key) {
this.setState({[key]: e.target.value});
}
I modified the code from this thread to make an example
class FormInput extends React.Component{
consturctor(props){
super(props);
this.state = {email:false,password:false}
}
handleOnChange(e,key) {
this.setState({[key]: e.target.value});
}
render() {
return
<form>
<input type="text" name="email" placeholder="Email" onChange={this.handleOnChange('email')} />
<input type="password" name="password" placeholder="Password" onChange={this.handleOnChange('password')}/>
<button type="button" onClick={this.handleLogin}>Zogin</button>
</form>;
}
}
A few ways to do this:
Add an attribute/or access the attribute from the element
Using this code:
class FormInput extends Component{
onChange(e) {
const { target } = e;
const key = target.getAttribute('name');
}
}
Bind the extra attribute (partials) when you create the onChange function
Using this code:
<input name='password' onChange={this.onChange.bind('password')} />
//or
<input name='password' onChange={(e) => this.onChange('password',e)} />
Do note that you would need to change the order of the onChange function
onChange(key,e) {
//key is passed here
}
This is usually not advisable because you would create the function on each render call. See if its fine on your case
List item
Lastly you can wrap the element and from there just pass what the caller needs on the onChange
class Input extends Component {
dispatchOnChange(e) {
const { props } = this;
const { name } = props;
const value = e.target.value;
props.onChange(name,value);
}
render() {
return <input {...this.props} onChange={this.dispatchOnChange}/>
}
}
//your render
<Input type="password" name="password" placeholder="Password" onChange={this.handleOnChange}/>
Hope this helps
You could create an anonymous function, calling handleOnChange with your custom key. That would look like:
<button type="button" onClick={(e) => this.handleLogin(e, index)}>
If you have not worked with anonymous functions before, this is telling JavaScript to create a new function on the fly during render, that takes a parameter e and calls this.handleLogin(e, index). In JavaScript, anonymous functions inherit scope, so the "this" keyword will be scoped correctly.