skip to Main Content

I have four input fields of an html form which the name attributes are extracted using the event handler onChangeHandler. these names are extracted using e.target.name . Now here is the issue, I want to update the state object by copying an initialState object into the state object but making sure the current input experiencing the onChange event is also updated. using e.target.name to set the property name does not work, but [e.target.name] works the magic.

why is this so? why does [e.target.name] work instead of e.target.name?

here is the code


const initialState = {
    displayName : '',
    email : '',
    password : '',
    password_confirmation: ''
}

function SignUpForm(){

    const [fieldState , setFieldState] = useState(initialState);
    const {displayName , email , password , password_confirmation} = fieldState;

    const onChangeHandler = (e) => {

        console.log(e)
        //updating state when it is an object
        //https://beta.reactjs.org/learn/updating-objects-in-state

        setFieldState({
            ...fieldState , //Copy the initial state
            [e.target.name] : e.target.value //but update this property
        })

    }

    return(
        <form>
            <input type="text" name="displayName" onChange={onChangeHandler} value={displayName}/>
            <input type="email" name="email" onChange={onChangeHandler} value={email}/>
            <input type="password" name="password" onChange={onChangeHandler} value={password}/>
            <input type="password" name="password_confirmation" onChange={onChangeHandler} value={password_confirmation}/>
        </form>
    );
}

export default SignUpForm```

2

Answers


  1. Chosen as BEST ANSWER

    Javascript allows you to put an expression in brackets [], that will be computed and used as the property name.

    const param = "size";
    
    const config = {
      [param]: 12
    };
    
    console.log(config); // {size: 12}
    

  2. In General, thats the way of adding dynamic property to an object, you need to wrap the prop. name with square brackets([]).

    let obj = {
    name: ‘ray’
    };

    obj[‘age’] = 20; // obj = {name: ‘ray’, age: 20};

    To access object property Dot(.) operator can use.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search