I
I
Ivan Simonov2021-05-23 17:46:13
React
Ivan Simonov, 2021-05-23 17:46:13

How to use React.useState in react class component?

hello there
is a code

class MyClass extends React.Component {
    constructor(props) {
        super(props);        
    }
    render() {
        const [current, setCurrent] = React.useState('one')
        return (
            <section className="section">
                <Tab value="one" active={current === 'one'} onClick={setCurrent}>One</Tab>
                <Tab value="two" active={current === 'two'} onClick={setCurrent}>Two</Tab>
            </section>
        )
    }
}

Resp. I get an error that I need to use function component.
Tell me how to use React.useStatein class component? Is it possible?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Shock, 2021-05-23
@ivan00007

Possibly, but in this case class components don't make life easier

class MyClass extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          current: 'one'
        };
    }
    render() {
        return (
            <section className="section">
                <Tab value="one" active={this.state.current === 'one'} onClick={() => this.setState({current: 'one'})}>One</Tab>
                <Tab value="two" active={this.state.current === 'two'} onClick={() => this.setState({current: 'two'})}>Two</Tab>
            </section>
        )
    }
}

R
Rodion Meshcheryakov, 2021-05-23
@rodionme

useStateis a hook, and hooks are only used in functional components.

import React from 'react';

function MyClass() {
    const [current, setCurrent] = React.useState('one');

    return (
        <section className="section">
            <Tab value="one" active={current === 'one'} onClick={setCurrent}>One</Tab>
            <Tab value="two" active={current === 'two'} onClick={setCurrent}>Two</Tab>
        </section>
    )
}

I believe that in your example it setCurrentpicks up the parameter from the valuecorresponding component on its own <Tab>.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question