Categories
React Answers

How to Set a Background Image With React Inline Styles?

Sometimes, we want to set a background image with React inline styles.

In this article, we’ll look at how to set a background image with React inline styles.

Set a Background Image With React Inline Styles

We can set the background image with inline styles by setting the style prop to an object with the backgroundImage property.

For instance, we can write:

import React from "react";

export default function App() {
  return (
    <div
      style={{
        backgroundImage:
          "url(https://i.picsum.photos/id/219/200/300.jpg?hmac=RGnJfbO2380zLCFSj2tm_q0vW0wtw67d0fhWHX2IoDk)",
        backgroundPosition: "center",
        backgroundSize: "cover",
        backgroundRepeat: "no-repeat",
        width: "200px",
        height: "200px"
      }}
    ></div>
  );
}

We set the backgroundImage to the url value of the image.

And we set the backgroundPosition to 'center' to center the background image.

backgroundSize is set to 'cover' to covert the div.

backgroundRepeat is set to 'no-repeat' to disable repetition.

width and height have the width and height of the div.

Conclusion

We can set the background image with inline styles by setting the style prop to an object with the backgroundImage property.

Categories
React Answers

How to Rerender the View on Browser Resize with React?

Sometimes, we want to re-render the view on browser resize with React.

In this article, we’ll look at how to re-render the view on browser resize with React.

Rerender the View on Browser Resize with React

We can use the useLayoutEffect to add the event listener that runs when the window resizes.

And in the window resize event handler, we can run our code to change a state to make the view rerender.

For instance, we can write:

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

const useWindowSize = () => {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    const updateSize = () => {
      setSize([window.innerWidth, window.innerHeight]);
    };
    window.addEventListener("resize", updateSize);
    updateSize();
    return () => window.removeEventListener("resize", updateSize);
  }, []);
  return size;
};

export default function App() {
  const [width, height] = useWindowSize();
  return (
    <span>
      Window size: {width} x {height}
    </span>
  );
}

We create the useWindowSize hook that has the size state.

In the useLayoutEffect hook callback, we create the updateSize function that calls setSize to set thje size state to an array with window.innerWidth and window.innerHeight , which has the width and height of the browser window respectively.

Then we call window.addEventListener with 'resize' to set updateSize as the window resize event listener.

Also, we return a function that calls window.removeEventListener to clear the resize event listener when the component unmounts.

Finally, we return the size at the end of the hook function.

Then in App , we destructure the width and height returned from the useWindowSize hook.

And then we render it in the span.

Now when the window resizes, we see its size change.

Conclusion

We can use the useLayoutEffect to add the event listener that runs when the window resizes.

And in the window resize event handler, we can run our code to change a state to make the view rerender.

Categories
React Answers

How to Show or Hide Elements or Components in React?

Sometimes, we want to show or hide elements or components with React.

In this article, we’ll look at how to show or hide elements or components with React.

Show or Hide Elements or Components in React

We can show or hide elements or components in React with the ternary operator.

For instance, we can write:

import React, { useState } from "react";

const Results = () => <div>Some Results</div>;

export default function App() {
  const [showResults, setShowResults] = useState(false);
  const onClick = () => setShowResults(true);
  return (
    <div>
      <input type="submit" value="Search" onClick={onClick} />
      {showResults ? <Results /> : null}
    </div>
  );
}

We have the Results component which we want to show after we click the Search button.

When we click the button, we run the onClick function which calls setShowResults with true to set showResults to true .

If showResults is true , then the Results component is rendered.

Otherwise, null , which is nothing, is rendered.

We can do the same thing with HTML elements.

Conclusion

We can show or hide elements or components in React with the ternary operator.

Categories
React Answers

How to Delete an Item from a State Array in a React Component?

Sometimes, we want to delete an item from a state array in a React component.

In this article, we’ll look at how to delete an item from a state array in a React component.

Delete an Item from a State Array in a React Component

We can return a new array within the state setter function’s callback to change a React component’s state array.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [names, setNames] = useState(["jane", "john", "james"]);

  return (
    <div className="App">
      <button
        onClick={() =>
          setNames((names) => names.filter((_, i) => i !== names.length - 1))
        }
      >
        delete
      </button>
      <div>{names.join(", ")}</div>
    </div>
  );
}

We have the names state array that we created with useState .

Then we have a button that has the onClick prop set to a function that calls setNames with a callback that returns the names array without the last element.

We remove the last element from the returned array by calling filter with a callback that checks whether i isn’t names.length — 1 .

This will update the names array with the array returned by filter .

And below that, we render the names entries in a string.

Now when we click on the button, we see the last name in the string removed.

Conclusion

We can return a new array within the state setter function’s callback to change a React component’s state array.

Categories
React Answers

How to Scroll to an Element in a React Component?

Sometimes, we want to scroll to an element in a React component.

In this article, we’ll look at how to scroll to an element in a React component.

Scroll to an Element in a React Component

We can scroll to an element by assigning a ref to it and calling scrollIntoView on it.

For instance, we can write:

import React, { useRef } from "react";

export default function App() {
  const myRef = useRef(null);

  const executeScroll = () => myRef.current.scrollIntoView();

  return (
    <>
      <button onClick={executeScroll}> Click to scroll </button>
      {Array(100)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
      <div ref={myRef}>Element to scroll to</div>
    </>
  );
}

We create myRef with the useRef hook,

Then we create the executeScroll method that calls scrollIntoView on the element that’s been assigned the ref.

myRef.current has the element we assigned the ref to as its value.

We assign the ref by assigning the ref prop with myRef .

Then we set the onClick prop to executeScroll to run executeScroll when we click on the button.

Now when we click on the button, we should scroll to the element that’s assigned to myRef .

Conclusion

We can scroll to an element by assigning a ref to it and calling scrollIntoView on it.