alex
alex

Reputation: 4914

A simple form component with react.js. But onsubmit all fields always empty?

I am starting with react.js and I have this simple form but onSubmit the input fields are always empty?? Any tips/idea what I am overlooking?

import React, { Component } from 'react'

class PostForm extends Component {
    constructor(props) {
        super(props)

        this.state = {
            userID: '',
            title: '',
            body: ''
        }
        
        // this.submitHandler = this.submitHandler.bind(this);
    }

    changeHandler = e => {
        this.setState = ({ [e.target.name]: e.target.defaultValue })
    }

    submitHandler = e => {
        e.preventDefault()
        console.log(this.state) //<-- always empty fields???
    }

    render() {
        const { userID, title, body } = this.state

        return (
            <div>
                <form onSubmit={this.submitHandler}>
                    <div>
                        <input type="text" name="userID" defaultValue={userID} onChange={this.changeHandler} />
                    </div>
                    <div>
                        <input type="text" name="title" defaultValue={title} onChange={this.changeHandler} />
                    </div>
                    <div>
                        <input type="text" name="body" defaultValue={body} onChange={this.changeHandler} />
                    </div>
                    <button type="submit">Submit</button>
                </form>
            </div>
        )
    }
}

export default PostForm

Upvotes: 0

Views: 263

Answers (2)

zhulien
zhulien

Reputation: 5695

this.setState is a function and instead of calling it you're trying to assign a variable to it. Change your changeHandler function to:

changeHandler = e => {
    this.setState((state) => {
        return {
            ...state,
            [e.target.name]: e.target.value
        };
    })
};

Also, like @Alex pointed out, you should add value={<state-variable>} to your inputs in order to make them controlled:

<input type="text" name="userID" value={userID} onChange={this.changeHandler} />

This will also cover your default value case as it will apply the initial values from your state anyway.

Upvotes: 1

Alex Chirkin
Alex Chirkin

Reputation: 103

Here you set to state default value (it's emty). Change to e.target.value

changeHandler = e => {
    this.setState = ({ [e.target.name]: e.target.defaultValue })
   }

And change this defaultValue={userID} to value={userID} on every input

<input type="text" name="userID" defaultValue={userID} onChange= 
{this.changeHandler} />

Upvotes: 1

Related Questions