react router

[React.js] Wrapping React-Router in Component

Link element of react-router is to create links to navigate like what <a href=”” /> do. What if we want to do a navigation, but not from a link, by Javascript.

The Hero History.push()

Navigation is implemented by history.push(), but using router.history within the children tree of Router root, it is not as easy as I think.

As Martti Laine ‘s answer, there are three ways to approach:

— 1. Use the withRouter higher-order component

— 2. Use composition and render a <Route>

— 3. Use the context*

Wrapping React Router to component

After a lot of research, wrapping Router into the existed components to use history is the best implementation for my situation, touching the least code.

// ButtonClick.js component
import React, { Component } from 'react'
import { Route } from 'react-router-dom'
class ButtonClick extends Component {
handleClick = () => {
const {history, id} = this.props
return history.push(`/user/${id}`)
   render() {
<div className="someStyle">
<a onClick={this.handleCreate}> Click Me </a>
export default (props) => {
return <Route
render={({ history}) => {
const _props = {...props, history}
return <ButtonClick {..._props}/>