Categories
React Answers

How to access styles of an element from React?

Sometimes, we want to access styles of an element from React.

In this article, we’ll look at how to access styles of an element from React.

How to access styles of an element from React?

To access styles of an element from React, we can assign a ref to the element that we want to get the styles for.

And then we can use the window.getComputedStyle method to get the style from the element’s ref.

For instance, we write:

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

export default function App() {
  const ref = useRef();
  useEffect(() => {
    const computed = window
      .getComputedStyle(ref.current)
      .getPropertyValue("border-radius");
    console.log(computed);
  }, []);

  return (
    <div ref={ref} style={{ borderRadius: "5px" }}>
      hello world
    </div>
  );
}

We create a ref with the useRef hook.

Then we assign the ref to the div.

Next, we get the border-radius style of the div when the div is rendered by using:

const computed = window
   .getComputedStyle(ref.current)
   .getPropertyValue("border-radius");

We put the code in the useEffect callback so it’ll run when the component is mounted.

As a result, we get that computed is 5px since we set the borderRadius of the div to 5px.

Conclusion

To access styles of an element from React, we can assign a ref to the element that we want to get the styles for.

And then we can use the window.getComputedStyle method to get the style from the element’s ref.

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 formatOptionLabel prop to a component that renders the option the way we want.

For instance, we write:

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

const options = [
  { value: "Abe", label: "Abe", customAbbreviation: "A" },
  { value: "John", label: "John", customAbbreviation: "J" },
  { value: "Dustin", label: "Dustin", customAbbreviation: "D" }
];

const formatOptionLabel = ({ value, label, customAbbreviation }) => (
  <div style={{ display: "flex" }}>
    <div>{label}</div>
    <div style={{ marginLeft: "10px", color: "#ccc" }}>
      {customAbbreviation}
    </div>
  </div>
);

export default function App() {
  return (
    <div>
      <Select
        defaultValue={options[0]}
        formatOptionLabel={formatOptionLabel}
        options={options}
      />
    </div>
  );
}

We have the options array which we use as the options for the Select drop down.

Next, we define the formatOptionLabel component that renders the options the way we want.

The props comes from the entry in the options array.

Then, we add the Select component to App and set the formatOptionLabel prop to formatOptionLabel.

And we set the options prop to options so that the options are rendered and the props are available to formatOptionLabel.

Conclusion

To replace components for custom option content with React-Select, we can set the formatOptionLabel prop to a component that renders the option the way we want.

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.