I'm trying to pass a prop through a React Router Link Component, however when declaring useLocation
hook that comes with the React Router in my class component:
const location = useLocation()
const { from } = location.state
I get this error React Hook "useLocation" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function
Would it be possible to use useLocation
in my class Component, or would I have to convert to a functional component ?
Here is my app Structure:
My functional component using the React Router Link Component to pass in a prop to my class component:
import { Button } from '@mui/material';
import React from 'react'
import { Link, useLocation } from 'react-router-dom';
import icon from './images/icon.png';
import Main from './Main';
import Screen from './Screen';
const Success = ({ nextStep, handleChange, values, props }) => {
// ...
const current = new Date();
const date = `${current.getDate()}/${current.getMonth()+1}/${current.getFullYear()}`;
// ...
return(
<div>
<p>You have successfully bought: </p>
<p>{`${values.payAmount}`} BTC on {date}</p>
<Link to='/App' state={{ from: values.payAmount }}>
<Button color="primary"
variant="contained"
style={{ padding:'9px 60px'}}
>Done</Button>
</Link>
</div>
)
}
export default Success;
My class component using the useLocation
hook in order to receive data: (this is where I get the error)
import React, { Component } from 'react'
import { Link, useLocation } from 'react-router-dom';
class Main extends React.Component {
render() {
const location = useLocation()
const { from } = location.state
return (
<div >
<h1> My Accounts </h1>
<p> You know have {from} in your wallet. </p>
</div>
)
}
}
export default withStyles(styles, { withTheme: true })(Main);