Categories
React Answers

How to remove an element from DOM after set amount of time with React?

Sometimes, we want to remove an element from DOM after set amount of time with React.

In this article, we’ll look at how to remove an element from DOM after set amount of time with React.

How to remove an element from DOM after set amount of time with React?

To remove an element from DOM after set amount of time with React, we can use the setTimeout function in the useEffect hook callback.

For instance, we write:

import React, { useEffect, useState } from "react";

const Expire = ({ delay, children }) => {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setVisible(false);
    }, delay);
  }, [delay]);

  return visible ? <div>{children}</div> : <div />;
};

export default function App() {
  return <Expire delay={1000}>123</Expire>;
}

We create the Expire component that has the visible state to control whether the div is visible or not.

Next, we call useEffect with a callback that calls setTimeout with a callback that calls setVisible to false to set visible to false.

We use delay as the value of the delay to run the setTimeout callback.

Now we only display the div with the children inside only when visible is true.

Finally, in App, we render the Expire component with delay set to 1000 to show 123 for 1 second.

Conclusion

To remove an element from DOM after set amount of time with React, we can use the setTimeout function in the useEffect hook callback.

Categories
React Answers

How to replace components for custom option content with React-Select?

Sometimes, we want to replace components for custom option content with React-Select.

In this article, we’ll look at how to replace components for custom option content with React-Select.

How to replace components for custom option content with React-Select?

To replace components for custom option content with React-Select, we can set the components prop to an object with the Option property set to the component we want to render for each option.

For instance, we write:

import React from "react";
import Select from "react-select";

const options = [
  { label: "Apple", value: "apple" },
  { label: "Orange", value: "orange" },
  { label: "Grape", value: "grape" },
  { label: "Pear", value: "pear" },
  { label: "Banana", value: "banana" }
];

const MyOption = (props) => {
  const { innerProps, innerRef } = props;
  return (
    <article ref={innerRef} {...innerProps}>
      <h4>{props.data.label}</h4>
    </article>
  );
};

export default function App() {
  return (
    <form>
      <Select options={options} components={{ Option: MyOption }} />
    </form>
  );
}

We create the MyOption component that destructures the innerProps and innerRef from the props.

Then both are spread as props of the root element of the option component to let us render it as options in the drop down.

props.data has the options object in options.

Next, we set components to an object with the Option property set to MyOption to use MyOption to render each drop down option.

Conclusion

To replace components for custom option content with React-Select, we can set the components prop to an object with the Option property set to the component we want to render for each option.

Categories
React Answers

How to render array of components with React?

Sometimes, we want to render array of components with React.

In this article, we’ll look at how to render array of components with React.

How to render array of components with React?

To render array of components with React, we can wrap the components in a fragment.

For instance, we write:

import React from "react";

const Foo = () => <p>foo</p>;

const Bar = () => <p>bar</p>;

const Baz = () => <p>baz</p>;

export default function App() {
  return (
    <>
      <Foo />
      <Bar />
      <Baz />
    </>
  );
}

to render the Foo, Bar, and Baz components inside the fragment.

And <> and </> are the opening and closing tags of the fragment respectively.

Conclusion

To render array of components with React, we can wrap the components in a fragment.

Categories
React Answers

How to parse data from JSON in React?

Sometimes, we want to parse data from JSON in React.

In this article, we’ll look at how to parse data from JSON in React.

How to parse data from JSON in React?

To parse data from JSON in React, we can use the JSON.parse method.

For instance, we write:

import React from "react";

const str = `{"name": "abc","messages":["msg 1","msg 2","msg 3"],"age":100}
`;

const myObject = JSON.parse(str);

export default function App() {
  console.log(myObject);

  return <div></div>;
}

We have the str JSON string that we parsed into a JavaScript object with JSON.parse.

Then we logged its value in App.

Conclusion

To parse data from JSON in React, we can use the JSON.parse method.

Categories
React Answers

How to read Excel files in React?

Sometimes, we want to read Excel files in React.

In this article, we’ll look at how to read Excel files in React.

How to read Excel files in React?

To read Excel files in React, we can use the xlsx package.

To install it, we run:

npm i xlsx

Then we can use it by writing:

import React from "react";
import * as XLSX from "xlsx";

export default function App() {
  const onChange = (e) => {
    const [file] = e.target.files;
    const reader = new FileReader();

    reader.onload = (evt) => {
      const bstr = evt.target.result;
      const wb = XLSX.read(bstr, { type: "binary" });
      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];
      const data = XLSX.utils.sheet_to_csv(ws, { header: 1 });
      console.log(data);
    };
    reader.readAsBinaryString(file);
  };
  return (
    <div>
      <input type="file" onChange={onChange} />
    </div>
  );
}

We define the onChange function that takes the file from the file input with:

const [file] = e.target.files;

Then we create a FileReader instance to read the file.

We set the reader.onload property to a function that reads the file.

We get the result with:

const bstr = evt.target.result;

Then we have:

const wb = XLSX.read(bstr, { type: "binary" });

to read the Excel file.

Next, we get the sheet name of the first sheet with:

const wsname = wb.SheetNames[0];

And we get the content of the first sheet with:

const ws = wb.Sheets[wsname];

Finally, we convert the Excel data to CSV with:

const data = XLSX.utils.sheet_to_csv(ws, { header: 1 });

And we call reader.readAsBinaryString with file to read the file.

Conclusion

To read Excel files in React, we can use the xlsx package.