camillalofroth
camillalofroth

Reputation: 229

What does withRouter and props in routes?

I'm pretty new to React and trying to understand what a component does that I am trying to use in a project.

I used useHistory from react-router before but this looks so different. And it also seems like props is being used. Is there somebody here that understand and can explain what this component does. And what withRouter does and if it's the same as useHistory?

Thank you!

import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

const LinkButton = (props) => {
  const {
    history,
    location,
    match,
    staticContext,
    to,
    onClick,
    // ⬆ filtering out props that `button` doesn’t know what to do with.
    ...rest
  } = props
  return (
    <button
      {...rest} // `children` is just another prop!
      onClick={(event) => {
        onClick && onClick(event)
        history.push(to)
      }}
    />
  )
}

LinkButton.propTypes = {
  to: PropTypes.string.isRequired,
  children: PropTypes.node.isRequired
}

export default withRouter(LinkButton)

Upvotes: 0

Views: 213

Answers (1)

Joseph D.
Joseph D.

Reputation: 12174

withRouter is a Higher Order Component (HOC) to inject router props (match, location, history) to the wrapped component, LinkButton.

Under the hood it uses RouterContext to populate the match, location, history to the wrapped component.

function withRouter(Component) {
  const C = props => {
    const { wrappedComponentRef, ...remainingProps } = props;

    return (
      <RouterContext.Consumer>
        {context => {
          return (
            <Component
              {...remainingProps}
              {...context} // pass context (match, location, history)
              ref={wrappedComponentRef}
            />
          );
        }}
      </RouterContext.Consumer>
    );
  };
}

While useHistory is just a custom hook in react router to use only history info within the function component.

Upvotes: 2

Related Questions