Reputation: 3123
I'm trying to convert my class Component to functional component but it doesn't work.
the problem comes from this line previousLocation = this.props.location;
how can i replace that in functional component
class App extends Component {
previousLocation = this.props.location; //the problem comes from here
render() {
const { location } = this.props;
const isModal = !!(
location.state &&
location.state.modal &&
this.previousLocation !== location
);
return (
<div>
<Switch location={isModal ? this.previousLocation : location}>
<Route exact path="/" component={Gallery} />
<Route exact path="/img/:id" component={Gallery} />
<Route exact path="/img" component={ModalPage} />
</Switch>
{isModal ? <Route path="/img/:id" component={ModalPage} /> : null}
</div>
);
}
}
what I'm trying to do
const App = (props) => {
const {previousLocation} = props.location;
const {location} = props;
const isModal = !!(
location.state &&
location.state.modal &&
previousLocation !== location
);
return (
<div>
<Switch location={isModal ? previousLocation : location}>
<Route exact path="/" component={Gallery}/>
<Route exact path="/img/:id" component={Gallery}/>
<Route exact path="/img" component={ModalPage}/>
</Switch>
{isModal ? <Route path="/img/:id" component={ModalPage}/> : null}
</div>
);
}
Upvotes: 0
Views: 100
Reputation: 202667
How to get the previous props or state
const usePrevious = value => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
Usage:
const App = ({ location }) => {
// get previous location and cache current location
const previousLocation = usePrevious(location);
const isModal = !!(
location.state &&
location.state.modal &&
previousLocation !== location
);
return (
<div>
<Switch location={isModal ? previousLocation : location}>
<Route exact path="/" component={Gallery}/>
<Route exact path="/img/:id" component={Gallery}/>
<Route exact path="/img" component={ModalPage}/>
</Switch>
{isModal ? <Route path="/img/:id" component={ModalPage}/> : null}
</div>
);
}
Upvotes: 2