Mediator
Mediator

Reputation: 15388

How use on change event in reactjs (hooks)

I need to change activeTab by onchange click on tab component. I think I need use reacts hooks. But I'm still can't understand how it is work. This code throw error

'handleChange is not defined'

function TobaccoLine({ match, location  }) {
   const activeTab = useSelector(state => location.state ? location.state.activeTab : 0);

   handleChange = (event, value) => {
      this.setState({ activeTab: value });
   }

    return (
         <div className="userProfile-wrapper">
                     <Tabs
                        value={activeTab}
                        onChange={handleChange}
                        variant="scrollable"
                        scrollButtons="off"
                        indicatorColor="primary"
                     >
...

Could you please help, because I'm already stuck? React JS v16+

Upvotes: 1

Views: 1010

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

This is not class component. The way you're using is public class method. Since, you are using it inside functional component, it is simply a function but the function is not being declared yet. So, you just need to define it:

const handleChange = (event, value) => {
  this.setState({ activeTab: value }); // Next problem: See below.
}

Earlier, you were getting handleChange is undefined coz, you were using without var,let or const declaration.

Next problem: You're using this.setState inside functional component which is not applicable. You'll need to use useState hook:

const [activeTab, setActiveTab] = useState('') // empty initial state, change it
// To set state:
setActiveTab('your value')
// To get state:
console.log(activeTab)

If you don't know about hooks, then you can learn more about it here.

Upvotes: 1

Related Questions