Search code examples
reactjsreact-routerreact-router-v4browser-history

What is the best way to change the URL onClick or onSubmit in a React Class Component?


I'm aware of the useHistory hook for functional components in React, but in my application I have a class component that I want to make able to change the URL.

Is there an equivalent of useHistory for class based components? If not, what is the accepted way to accomplish this?


Solution

  • May be you need something like this:

    import { withRouter } from 'react-router-dom'    
    
    export const Component = withRouter(({ history, location }) =>{
    
    })
    
    class Comp extends Component {
        render(){
            const { location, history } = this.props
        }
    }
    export default withRouter(Comp)
    

    A similar question answered here : https://stackoverflow.com/a/58122270/7306148