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

Categories
React Answers

How to Dynamically Load a Stylesheet with React?

Sometimes, we want to dynamically load a stylesheet with React.

In this article, we’ll look at how to dynamically load a stylesheet with React.

Dynamically Load a Stylesheet with React

To dynamically load a stylesheet with React, we can add a link element with the attributes we want.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [stylePath] = useState(
    "https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css"
  );

  return (
    <div>
      <link rel="stylesheet" type="text/css" href={stylePath} />
    </div>
  );
}

to create the stylePath state with the useState hook.

Its initial value is set to the URL of the stylesheet that we want to include.

Then we add a link element with the href prop set to stylePath to add the stylesheet at the given URL into the component.

Conclusion

To dynamically load a stylesheet with React, we can add a link element with the attributes we want.

Categories
React Answers

How to Map Only a Portion of an Array to Components in a React Component?

Sometimes, we want to map only a portion of an array to components in a React component.

In this article, we’ll look at how to map only a portion of an array to components in a React component.

Map Only a Portion of an Array to Components in a React Component

To map only a portion of an array to components in a React component, we can use the JavaScript array’s filter method to return an array of the items we want to map before calling map.

For instance, we write:

import React from "react";

export default function App() {
  const feed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

  return (
    <div>
      {feed
        .filter((item) => item <= 5)
        .map((filteredItem) => (
          <p key={filteredItem}>{filteredItem}</p>
        ))}
    </div>
  );
}

to create the feed array.

And we want to display the first 5 entries from feed.

To do this, we call filter with (item) => item <= 5 to return the first 5 elements.

Then we call map with a callback to return p elements with the content of the elements to display them on the screen.

Now we see:

1

2

3

4

5

on the screen

Conclusion

To map only a portion of an array to components in a React component, we can use the JavaScript array’s filter method to return an array of the items we want to map before calling map.