React Forms but

I’m trying to make a works cited maker with the authors in a separate component from the rest of the form.

Here is the repository, and Here is the deployed app. As you can see, whenever I fill out the author form field, it’s one keystroke behind.

Here are the event handlers:

changeAuthor(event){
    const {name, value} = event.target;
    this.setState({[name]: value});
    this.props.addAuthor(this.state)
}
   addAuthor(newAuthor){
        this.setState(prevState => {
            prevState.authors[0] = newAuthor;
            return prevState;
        })

    }

Forgive me if my issue seems a little unclear. I am new to React and have a little bit of trouble communicating.

setState is an async operation, i.e. it does not set state the moment is called, that happens on re-render.

1 Like

Thanks! That helped!

I have question to the code if I may be little off topic.
Could you describe how this part of code works

const {name, value} = event.target;
this.setState({[name]: value});

Line 1: Does name and value has same value ?
Line2: Why [name] is in array ? I thought we change the property of object state.

When dealing with an object, we can use bracket notation, so:

obj["firstName"]

is the same thing as:

obj.firstName

Here is a sample input field:

<input type="text" name="firstName">

When we enter the event into the event handler, it will have the name of firstName, or whatever we choose for the name property in the input. Because we are using bracket notation, it will look for that property in the object, state. Does that make sense?

Here is an article that explains it in more detail.

2 Likes

oh, ok, I think I get it. So [name] will work here as variable that searches in property of object and while name: would be treated as a title of parameter. Is it also a shorthand i suppoust ? How it knows in which object looking for. I guess its about setState implementation.

Thanks for fast response !

Yes, if I put ‘firstName’ as the name of the input element, then event.target.name will be ‘firstName’ and it will be looking for a property in the state called ‘firstName’.

This tutorial explains React forms really well.

1 Like

If you are still wobbly on this you can read this short article on the matter, this technique is called computed property names and it’s one of the new features of ES6.

1 Like