E
E
Egor Telnov2019-11-20 19:41:17
React
Egor Telnov, 2019-11-20 19:41:17

How to update state value using React Hooks?

Hello. Decided to delve into hooks. And there was a question in front of me. If, using a class component, in order to get the value from the input, I did this:

import React, {Component} from 'react';
class Test extends React.Component {
    constructor() {
        super();

        this.state = {
            someValue : ''
        };
    };

    handleInput = event => {
        this.setState({someValue : event.target.value});
    };

    render() {
        return (
            <input type="text" onInput = {this.handleInput}/>
        )
    }
}

then how to do it using the state hook?
I wrote a component like this:
const MyPosts = props => {
    const [newPost, useNewPost] = useState('');

    const handleInput = event => useNewPost(event.target.value);
    const addPost = () => {
        console.log(newPost);
    };

    return ( 
        <div>
            <textarea onInput = {HandleInput}></textarea>
            <p onClick = {addPost}>Добавить</p>
         </div>

but React swears that hooks cannot be used inside other js functions. How to be in such a situation? How to solve such a simple problem using the ideology of hooks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dev null, 2019-11-20
@telnov_magic

Linter swears at useNewPost, since this is not a hook, it should be renamed, for example, to setNewPost

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question