Search code examples
reactjssetstate

Simple react setState


I am trying to do this simple React app with the state.

It is throwing an error when I type something into the input: TypeError: Cannot read property 'value' of undefined

import React, { useState } from "react"

function Input() {
    const [inputValue, setInputValue] = useState("Enter input.")
    const pushInputValue = (event) => setInputValue(event.this.value)
    return (
        <div className="Input">
            <h3>Enter input.</h3>
            <input
                type="text"
                placeholder={inputValue}
                onChange={pushInputValue}
            ></input>
        </div>
    )
}
export default Input

Solution

  • Fix event.this.value to event.target.value

    import React, { useState } from "react";
    
    function Input() {
        const [inputValue, setInputValue] = useState("Enter input.");
        const pushInputValue = (event) => setInputValue(event.target.value);
        return (
            <div className="Input">
                <h3>Enter input.</h3>
                <input
                    type="text"
                    placeholder={inputValue}
                    onChange={pushInputValue}
                ></input>
            </div>
        );
    }
    export default Input;