Z
Z
zerabora2020-12-10 12:44:48
React
zerabora, 2020-12-10 12:44:48

Why is there an error when using useState?

The essence of the task: to add text from the input to the paragraph by pressing the button.

import React, {useState} from 'react'

const Task = () => {
    const [value, setValue] = useState();

    const handleChange = (e) => {
        setValue(()=>({value: e.target.value}));
    };

    const handleClick = () => {
        return value;
    };

    return <div>
        <input type='text' onChange = {handleChange} />
        <input type='submit' value ='click' onClick = {handleClick} />
        <p>{handleClick()}</p>
    </div>
};

export default Task;


I pass the text from the input to the paragraph: In this case, an error appears at the onChange stage of the input:
<p>{handleClick()}</p>

Uncaught Error: Objects are not valid as a React child (found: object with keys {value}). If you meant to render a collection of children, use an array instead.

How to fix the problem using functional component and hooks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tigran Abrahamyan, 2020-12-10
@zerabora

const [value, setValue] = useState('');
const [text, setText] = useState('');

const handleChange = (e) => setValue(e.target.value);
const handleClick = () => setText(value);

<p>{text}</p>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question