Categories
React Answers

How to redirect in React Router v6?

To redirect in React Router v6, we add the replace prop to the Route.

For instance, we write

import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";

//...
<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/lab" element={<Lab />} />
    <Route path="*" element={<Navigate to="/" replace />} />
  </Routes>
</BrowserRouter>

to add the * route that has the replace prop added to Navigate so that we redirect to the / route.

Then Home is rendered after the redirect is done.

Categories
React Answers

How to pass data from one component to another in React?

To pass data from one component to another in React, we pass it as a prop.

For instance, we write

<BigTextMobile data={data} />;

to pass the data state as the value of the data prop of the BigTextMobile from the parent component.

Categories
React Answers

How to add active class to button with React?

To add active class to button with React, we set the className of the button.

For instance, we write

<div>
  {buttons.map((name, index) => {
    return (
      <input
        type="button"
        className={active === name ? "active" : ""}
        value={name}
        onClick={() => someFunct(name)}
        key={name}
      />
    );
  })}
</div>

to add buttons by adding inputs with type button.

Then we apply the active class if the active value equals name.

When do something with name when we click the button

Categories
React Answers

How to use Google Analytics with React?

To use Google Analytics with React, we run the Google Analytics code in the useEffect callback.

For instance, we write

import React, { useEffect } from "react";
import { Router, Route } from "react-router-dom";
import { createBrowserHistory } from "history";
import ReactGA from "react-ga";

ReactGA.initialize(process.env.REACT_APP_GA_TRACKING_NO);
const browserHistory = createBrowserHistory();
browserHistory.listen((location, action) => {
  ReactGA.pageview(location.pathname + location.search);
});

const App = () => {
  useEffect(() => {
    ReactGA.pageview(window.location.pathname + window.location.search);
  }, []);

  return <div>Test</div>;
};

to call ReactGA.initialize to initialize Google Analytics.

Then we call ReactGA.pageview in the useEffect callback to record the URL the user went to when the component mounts.

Categories
React Answers

How to listen to local storage value changes in React?

To listen to local storage value changes in React, we listen to the storage event.

For instance, we write

window.addEventListener("storage", (e) => {
  this.setState({ auth: true });
});

to listen to the storage event by calling window.addEventListener with 'storage'.

And then we do whatever we want when it changes by calling it with a callback that runs when the event is triggered.