Will
Will

Reputation: 4705

Navigating Using React Router From a Button Outside the React App

I have a simple demo react app that uses react-router-dom (5.2) to show one of 3 "pages".

The app is included on a page that has a button:

index.html:

<button data-app-button data-sku='woo-beanie'>Click Me</button>

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

document.addEventListener('click', function (event) {    
    if (event.target.closest('button[data-app-button]')) {
      // send instructions to react
    }
});

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

I want to be able to navigate to a page in the react site, passing through the buttons data-attributes. How is this done with react and react-router ?

UPDATE

@Doppoio's solution works - as long as I'm on a different "page" in my react app. However I have a route like this:

  <Route
    path="/tryon/:id/:product_sku?">
  </Route>

If I start in app from a route of say /faqs and my external button navigates to /tryon/242/jumper-23 my component is awar of the product_sku property.

However when I'm on a page in app of /tryon/242 and then i click an external button to navigate to /tryon/242/jumper-23 the component should be aware of the jumper-23 optional parameter. Currently it isn't.

How do i make the Tryon component detect the change in url of just the optional parameter?

Upvotes: 0

Views: 95

Answers (1)

Doppio
Doppio

Reputation: 2188

Somewhere in your code under Router, you can add history to window object. And call it from there.

const SomeComponentInsideRouter = () => {
  const history = useHistory();
  useEffect(() => {
    window.reactHistory = history; // Add reference to history via window object.
  }, []);
  return null;
};

And call it via window.reactHistory

document.addEventListener("click", function (event) {
  if (event.target.closest("button[data-app-button]")) {
    // send instructions to react
    window.reactHistory.push("/about");
  }
});

Here's sandbox link https://codesandbox.io/s/happy-ganguly-b0u2o?file=/src/index.js

Update to mention changed props:

Changes to the props can be detected using componentDidUpdate

https://reactjs.org/docs/react-component.html#componentdidupdate

Upvotes: 1

Related Questions