Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use useHistory() hook in Class Component Type Script

Hello I am trying to use

this.history.push({
                    pathname: `/search-results`,
                    search: `${job}$${location}`
                  }) 

In my class component that is using type script . However it is giving me back an error of Property 'history' does not exist on type 'Banner'. TS2339

I can see other examples of functional component, you can do const history = useHistory(); and use history.push from hook.

How can I do the same thing in class component?

like image 516
julz oh Avatar asked Jan 07 '21 21:01

julz oh


People also ask

Can I use hook in class component?

You can't use Hooks inside a class component, but you can definitely mix classes and function components with Hooks in a single tree. Whether a component is a class or a function that uses Hooks is an implementation detail of that component.

How do you use useHistory Hooks?

All we need to do is to call the useHistory hook inside a functional component: import { useHistory } from 'react-router-dom'; const App = () => { const history = useHistory(); const redirect = () => { history. push('/login'); } return ( <div> <h1>Hi there!

How do you use a hook in React component?

Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders.

Can we write useEffect in class component?

Using useEffect to apply lifecycle methods in functional components. In class components, we have lifecycle methods to perform actions in a specific lifecycle stage of our component. For us to do something similar and perform side effects in our functional components, the React team created the useEffect Hook.


1 Answers

Hooks are not designed to work with class based components.

However, react-router has other methods to support class based components such as the withRouter higher order component.

That said, use functional components and hooks if you can. They are the React standard going forward.

like image 170
Alex Wayne Avatar answered Oct 12 '22 08:10

Alex Wayne