How to Use React Hooks in React Classic 'Class' Component

Using a React hook inside a class component

According to React docs you can't use hooks inside a class component:

https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both

What you can do is to wrap your class component with a functional component and pass props to it

for example:

class MyClass extends React.Component{
render(){
<div>{this.props.user}</div>
}
}

const funcComp = () => {
const [user, setUser] = useState();

useEffect(() => {
auth.Context.loadUser().then(user => setUser(user))
}, [setUser]);

return <MyClass user={user}/>
}

Can I use useState hook in class component?

You cannot use useState() hook in a Class based component. To do so switch to a functional based component.

You can create a functional component as below /p>

import React, { useState } from "react";
import ReactDOM from "react-dom";

const Message = () => {
const [show, setShow] = useState(false);

const toggleVisibility = () => {
setShow(!show);
};

return (
<React.Fragment>
<a onClick={toggleVisibility} href="#">
Want to buy a new car?
</a>
{show && <p>Call +11 22 33 44 now!</p>}
</React.Fragment>
);
};

Using React Hooks in classes

React hooks for state management are used in function components.
In your case you can go with the old school state object:

constructor(props) {
super(props);
this.state = {
show: false,
}
}

If you want to use React Hooks instead do this:

const Projects = (props) => {
const [show, setShow] = useState(false);

const handleClose = () => setShow(false);
const handleShow = () => setShow(true);

return (
<div class="projects-section" id="projects">
<img className="project-image" src="assets/UAS-frontend.png" onClick={handleShow}/>
<Modal show={show} onHide={handleClose}> //Where I get the error
<Modal.Header closeButton></Modal.Header>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary" onClick={handleClose}>
Save Changes
</Button>
</Modal.Footer>
</Modal>
</div>
)
}

Call method of functional component in a class

You cannot call navigate from UserStore class, and you shouldn't, better to call it inside LoginForm

function handleSubmit() {
userStore
.login(info)
.then(() => navigate('/restaurant'))
.catch(error => setError('Invalid Email or Password'));
}

Another approach is to pass a callback

function handleSubmit() {
userStore
.login(info, () => navigate('/restaurant'))
.catch(error => setError('Invalid Email or Password'));
}

// UserStore class

//...
login = async (creds: UserFormValues, callback) => {
try {
const user = await agent.Account.login(creds);
store.commonStore.setToken(user.token);
runInAction(() => this.user = user);
callback && callback()
console.log(user);
} catch (error) {
throw error;
}
}
//...

Should I move away from classes when using export classes with hooks?

Revert to what you had before, hooks are only usable inside React Function components.

// Correct, function component
export function Counter() {

// Incorrect, class component
export default class Counter extends React.Component<unknown> {
render(): {

The linting issue is #2, "breaking the Rules of Hooks". Specifically this is violating Only Call Hooks from React Functions (your second example is a React Class not a React Function).

React - Invalid hook call & class Component

React hooks can't be called from class components.

You can either convert said class component to a function component, or leave it as a class component and manage state the good ol' class-component way. Converting to a function should be preferred.

It seems the sandbox doesn't have all the files, so I can't know for sure, but i believe this might work:

import * as React from "react";
import "./styles.css";
import Father from "../src/components/father";
import global from "./global";
import extendDiv from "./extendDiv";

function App(props) {
let [dateVar, setDateVar] = React.useState({ date: new Date() })
global.isDivExtended = extendDiv();

return (
<>
<Father></Father>
</>
)
}

export default App;

Alternatively, you can write a higher-order component wrapper for your hook, so that you can pass the logic of a hook as a prop to your class component, as explained here. However, if possible, I would suggest avoiding it; it's messy and it's harder to test. Function components are way more fun to write (and read), plus it seems they are the future of React.



Related Topics



Leave a reply



Submit