Answer the question
In order to leave comments, you need to log in
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>
)
}
}
function component
. React.useState
in class component
? Is it possible?
Answer the question
In order to leave comments, you need to log in
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>
)
}
}
useState
is 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>
)
}
setCurrent
picks up the parameter from the value
corresponding component on its own <Tab>
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question