I am new to react and javascript. I have been learning react and react router and a tutorial i was following was using withRouter. Anyway, I found some code how to reimplement withRouter as it is no longer supported. My question is the following. How does the internal function get the props argument. Where does it come from? Thank you all in advance for the response, I have been stuck on this for a while.
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
And this is the whole snippet of the Component code:
import { Routes, Route, Redirect} from 'react-router-dom'
import { connect } from 'react-redux';
import React, { Component } from 'react';
import {
useLocation,
useNavigate,
useParams
} from "react-router-dom";
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
return ComponentWithRouterProp;
}
const mapStateToProps = state => {
return {
dishes: state.dishes
}
}
const HomePage = () => {
return (
<div>home page component</div>
);
}
class MainPage extends Component {
constructor(props) {
super(props);
}
render() {
return(
<div>
<div>main component {this.props.dishes}</div>
<Routes>
<Route path='/home' element={<HomePage />} />
</Routes>
</div>
);
}
}
export default withRouter(connect(mapStateToProps)(MainPage));
You are basically asking how Higher Order Components (HOCs) work. HOCs are just special Higher Order Functions. In other words, they are functions that return another function.
Take the basic HOC example:
const withExample => Component => props => {
... maybe some logic ...
return <Component {...props} />;
};
withExample is called and passed a React component as an argument:
const MyExample = withExample(BaseExample);
This returns a function, i.e. a React component with this definition:
const MyExample = props => {
... maybe some logic ...
return <BaseExample {...props} {...additionalProps} />;
};
This is just a regular React function component, the props come just like they do for any other React component.
<MyExample prop1="prop1" prop2={23} />
In your code example both withRouter and connect are HOCs, each taking a React component, augmenting/injecting additional props, and returns the decorated component.