Categories
React Answers

How to Conditionally Apply Class Attribute Values with React?

Sometimes, we want to set the class attribute conditionally within our React component.

In this article, we’ll look at how to set the class attribute conditionally within our React component.

Conditionally Apply Class Attribute Values with React

We can set the className prop conditionally to set the class attribute of an element conditionally.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [show, setShow] = useState(false);

  return (
    <>
      <style>
        {`
          .is-shown {
            display: block
          }

          .is-hidden {
            display: none
          }
        `}
      </style>
      <button onClick={() => setShow((s) => !s)}>toggle</button>
      <div className={show ? "is-shown" : "is-hidden"}>hello</div>
    </>
  );
}

We have the styles for the is-shown and is-hidden class in the style element.

Then we have a button that calls setShow to toggle the show state between true and false .

And then we set className to 'is-shown' is show is true and 'is-hidden' otherwise.

Now when we click on the button, we see the div being shown or hidden because we applied the class according to the value of show .

Conclusion

We can set the className prop conditionally to set the class attribute of an element conditionally.

Categories
React Answers

How to Update the Style of a Component on Scroll in React?

Sometimes, we want to update the style of a component on scroll with React.

In this article, we’ll look at how to update the style of a component on scroll with React.

Update the Style of a Component on Scroll in React

We can add a scroll event listener into the useEffect hook callback to listen for the scroll event.

For instance, we can write:

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

export default function App() {
  const [offset, setOffset] = useState(0);

  useEffect(() => {
    window.onscroll = () => {
      setOffset(window.pageYOffset);
    };
  }, []);

  console.log(offset);

  return (
    <div>
      {Array(100)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

We have the offset state which we create with the useState hook.

Then we call the useEffect hook with a callback that sets the window.onscroll property to a function that calls setOffset to set the offset to the scroll position.

window.pageYOffset has the vertical scroll position of the browser window.

We then log the offset with console log.

And we render some content that requires scrolling to view in the return statement.

Now when we scroll up or down, we see offset logged from the console log.

Conclusion

We can add a scroll event listener into the useEffect hook callback to listen for the scroll event.

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.