Categories
React Answers

How to get the dimensions of image with React?

Sometimes, we want to get the dimensions of image with React.

In this article, we’ll look at how to get the dimensions of image with React.

How to get the dimensions of image with React?

To get the dimensions of image with React, we can get it from the load event handler of the image.

For instance, we write:

import React from "react";

export default function App() {
  const onImgLoad = ({ target: img }) => {
    const { offsetHeight, offsetWidth } = img;
    console.log(offsetHeight, offsetWidth);
  };

  return (
    <div>
      <img
        onLoad={onImgLoad}
        alt=""
        src="https://i.picsum.photos/id/360/200/300.jpg?hmac=Fl1CgUfxrFjmcS1trYDG80XpEjYixcXfc2uTtCxFkDw"
      />
    </div>
  );
}

We define the onImgLoad function that gets the image from the target property.

Then we destructure the offsetHeight and offsetWidth properties from the image.

Next, we log the height and width with console.log.

Finally, we set the onLoad prop’s value to the onImgLoad function so onImgLoad is run when the image loads successfully.

Conclusion

To get the dimensions of image with React, we can get it from the load event handler of the image.

Categories
React Answers

How to read a text file in React?

Sometimes, we want to read a text file in React.

In this article, we’ll look at how to read a text file in React.

How to read a text file in React?

To read a text file in React, we can use the FileReader constructor.

For instance, we write:

import React from "react";

export default function App() {
  const showFile = (e) => {
    e.preventDefault();
    const reader = new FileReader();
    reader.onload = (e) => {
      const text = e.target.result;
      console.log(text);
    };
    reader.readAsText(e.target.files[0]);
  };

  return (
    <div>
      <input type="file" onChange={showFile} />
    </div>
  );
}

to define the showFile function that gets the selected file from e.target.files.

Then we create a new FileReader instance and assign it to reader.

Next, we set reader.onload to a function that runs when the file content is read.

We get the file content from e.target.result.

We call reader.readAsText to read the text from the selected file.

Finally, we add a file input and set its onChange prop to showFile so that showFile runs when we select a file.

Conclusion

To read a text file in React, we can use the FileReader constructor.

Categories
React Answers

How to conditionally render multiple child components with React?

Sometimes, we want to conditionally render multiple child components with React.

In this article, we’ll look at how to conditionally render multiple child components with React.

How to conditionally render multiple child components with React?

To conditionally render multiple child components with React, we can render components in an array.

And then we can use a state to control when the components are displayed.

For instance, we write:

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

export default function App() {
  const [visible, setVisible] = useState(true);

  return (
    <>
      <button onClick={() => setVisible((v) => !v)}>toggle</button>
      {visible ? [<p>foo</p>, <p>bar</p>, <p>baz</p>] : null}
    </>
  );
}

We define the visible state with the useState hook.

And we render 3 p elements if visible is true and null otherwise.

Finally, we add a button that calls setVisible to toggle the value of visible when we click on it.

Conclusion

To conditionally render multiple child components with React, we can render components in an array.

And then we can use a state to control when the components are displayed.

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.