How to wrap a react-router Link in an HTML button with JavaScript?

Spread the love

Sometimes, we want to wrap a react-router Link in an HTML button with JavaScript.

In this article, we’ll look at how to wrap a react-router Link in an HTML button with JavaScript.

How to wrap a react-router Link in an HTML button with JavaScript?

To wrap a react-router Link in an HTML button with JavaScript, we create a component.

For instance, we write

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

const LinkButton = (props) => {
  const { history, location, match, staticContext, to, onClick, ...rest } =
    props;
  return (
    <button
      {...rest}
      onClick={(event) => {
        onClick && onClick(event);
        history.push(to);
      }}
    />
  );
};

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

export default withRouter(LinkButton);

to create the LinkButton component that calls onClick if it’s defined when we click on the button.

And we call history.push toi navigate to the to URL.

We call withRouter with LinkButton to add the history prop to the component.

We then use it by writing

<LinkButton
  to="/path/to/page"
  onClick={(event) => {
    console.log("custom event here!", event);
  }}
>
  Push My Buttons
</LinkButton>

to add the button.

Conclusion

To wrap a react-router Link in an HTML button with JavaScript, we create a component.

Leave a Reply

Your email address will not be published.