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.

Categories
React Answers

How to enable CORS in a React App with Node.js backend?

To enable CORS in a React App with Node.js backend, we use the cors package.

To install it, we run

npm i cors

Then we use it by writing

const express = require("express");
const request = require("request");
const cors = require("cors");
const app = express();

app.use(cors());

app.use("/", (req, res) => {
  //...
});

app.listen(80, () => {
  console.log("CORS-enabled web server listening on port 80");
});

We add the cors middleware with

app.use(cors());

to enable CORS

Categories
React Answers

How to get row item on checkbox selection in React MUI DataGrid?

To get row item on checkbox selection in React MUI DataGrid, we set the onSelectionModelChange prop to a function to get the selected items.

For instance, we write

const App = () => {
  //...
  return (
    <>
      <DataGrid
        rows={rows}
        onSelectionModelChange={(ids) => {
          const selectedIDs = new Set(ids);
          const selectedRowData = rows.filter((row) =>
            selectedIDs.has(row.id.toString())
          );
          console.log(selectedRowData);
        }}
      >
        ...
      </DataGrid>
    </>
  );
};

export default ThemeSelector;

to set onSelectionModelChange to a function that gets the select row IDs from the ids parameter.

Then we can get the selected rows with

const selectedRowData = rows.filter((row) =>
  selectedIDs.has(row.id.toString())
);
Categories
React Answers

How to add conditional CSS in create-react-app?

To add conditional CSS in create-react-app, we can load CSS files dynamically.

For instance, we write

import React from "react";

const Theme1 = React.lazy(() => import("./Theme1"));
const Theme2 = React.lazy(() => import("./Theme2"));

const ThemeSelector: React.FC = ({ children }) => (
  <>
    <React.Suspense fallback={() => null}>
      {shouldRenderTheme1 && <Theme1 />}
      {shouldRenderTheme2 && <Theme2 />}
    </React.Suspense>
    {children}
  </>
);

export default ThemeSelector;

to import the Theme1 and Theme2 CSS files with

const Theme1 = React.lazy(() => import("./Theme1"));
const Theme2 = React.lazy(() => import("./Theme2"));

Then we render Theme1 or Theme2 according to the values of shouldRenderTheme1 and shouldRenderTheme2