Anders
Anders

Reputation: 1042

React router 'to' through props in const

I suspect this is more about React (or JS) than routing.

To avoid props collision, I am using forwardRef, defined in a const. The 'to' I want to set through props passed from parent component, and I cannot get this work. In the example below, where it says to={props.toUrl} it only works if it is to='/hello'. How do I do this, so I can use the ButtonRouter component from the Demo component?

import React from "react";
import { MemoryRouter as Router } from "react-router";
import { Link } from "react-router-dom";
import Button from "@material-ui/core/Button";

const CollisionLink = React.forwardRef((props, ref) => (
  <Link innerRef={ref} to={props.toUrl} {...props} />
));

function ButtonRouter(props) {
  return (
    <Router>
      <Button component={CollisionLink}>Routing w/o props collision</Button>
    </Router>
  );
}

export default function Demo() {
  return <ButtonRouter toUrl="/hello" />;
}

Upvotes: 0

Views: 32

Answers (1)

Clarity
Clarity

Reputation: 10873

I think you might be missing props from ButtonRouter:

function ButtonRouter(props) {
  return (
    <Router>
      <Button component={(routerProps) => <CollisionLink {...routerProps} {...props} />}>Routing w/o props collision</Button>
    </Router>
  );
}

Upvotes: 1

Related Questions