Categories
React Answers

How to conditionally render items based on viewport size in React?

Sometimes, we want to conditionally render items based on viewport size in React.

In this article, we’ll look at how to conditionally render items based on viewport size in React.

How to conditionally render items based on viewport size in React?

To conditionally render items based on viewport size in React, we can listen to the resize event emitted by window.

For instance, we write:

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

export default function App() {
  const [isDesktop, setDesktop] = useState(window.innerWidth > 650);

  const updateMedia = () => {
    setDesktop(window.innerWidth > 650);
  };

  useEffect(() => {
    window.addEventListener("resize", updateMedia);
    return () => window.removeEventListener("resize", updateMedia);
  });

  return (
    <div>
      {isDesktop ? (
        <div>I show on 651px or higher</div>
      ) : (
        <div>I show on 650px or lower</div>
      )}
    </div>
  );
}

We create the isDesktop state which is set to window.innerWidth > 650 initially.

Then we define the updateMedia function that calls setDesktop with window.innerWidth > 650.

Then we call useEffect with a callback that attaches the resize event listener to window with addEventListener.

We use updateMedia as the resize event listener.

In updateMedia, we call setDesktop with window.innerWidth > 650 to check if we’re in a desktop sized screen.

Also, we return a function to calls window.removeEventListener to clear the event listener.

Finally, we render the content we want based on the value of isDesktop.

Conclusion

To conditionally render items based on viewport size in React, we can listen to the resize event emitted by window.

Categories
React Answers

How to print a React component on click of a button?

Sometimes, we want to print a React component on click of a button.

In this article, we’ll look at how to print a React component on click of a button.

How to print a React component on click of a button?

To print a React component on click of a button, we can use the react-to-print library.

To install it, we run:

npm i react-to-print

Then we write:

import React, { forwardRef, useRef } from "react";
import ReactToPrint, { PrintContextConsumer } from "react-to-print";

const ComponentToPrint = forwardRef((props, ref) => {
  return <div ref={ref}>hello world</div>;
});

export default function App() {
  const ref = useRef();

  return (
    <div>
      <ReactToPrint content={() => ref.current}>
        <PrintContextConsumer>
          {({ handlePrint }) => (
            <button onClick={handlePrint}>Print this out!</button>
          )}
        </PrintContextConsumer>
      </ReactToPrint>
      <ComponentToPrint ref={ref} />
    </div>
  );
}

to use it.

We wrap the component that triggers the opening of the print dialog in the PrintContextConsumer.

And we wrap the PrintContextConsumer with the ReactToPrint component.

We set the content prop to a function that returns the ref.current value of the component we want to print when we click on the button.

We make the button open the print dialog by setting onClick to handlePrint.

Next, we set the ref prop of the element we want to print as the value of the ref prop.

Conclusion

To print a React component on click of a button, we can use the react-to-print library.

Categories
React Answers

How to get the value of checkbox using a ref in React?

Sometimes, we want to get the value of checkbox using a ref in React.

In this article, we’ll look at how to get the value of checkbox using a ref in React.

How to get the value of checkbox using a ref in React?

To get the value of checkbox using a ref in React, we can use the checked property of the checkbox.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const checkboxRef = useRef();

  const save = () => {
    console.log(checkboxRef.current.checked);
  };

  return (
    <div>
      <div>
        <label>
          <input type="checkbox" ref={checkboxRef} /> Check me out
        </label>
      </div>
      <button onClick={save}>Submit</button>
    </div>
  );
}

We create the checkboxRef with the useRef hook.

Then we assign the ref prop to checkboxRef to assign the checkbox as the value of checkboxRef.current.

Next, we define the save function to logged the checked value of the checkbox, which is stored in checkboxRef.current.checked.

Finally, we assign the onClick prop of the button to the save function to run it when we click it.

Therefore, when we check or uncheck the checkbox and click Submit, we should see the checked value logged.

Conclusion

To get the value of checkbox using a ref in React, we can use the checked property of the checkbox.

Categories
React Answers

How to fix ‘Static HTML elements with event handlers require a role.’ warning in React?

Sometimes, we want to fix ‘Static HTML elements with event handlers require a role.’ warning in React.

In this article, we’ll look at how to fix ‘Static HTML elements with event handlers require a role.’ warning in React.

How to fix ‘Static HTML elements with event handlers require a role.’ warning in React?

To fix ‘Static HTML elements with event handlers require a role.’ warning in React, we should set the role attribute of the a element.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div>
      <a role="button" onClick={() => alert("hello")}>
        hello
      </a>
    </div>
  );
}

to set the role attribute of the a element to button.

Conclusion

To fix ‘Static HTML elements with event handlers require a role.’ warning in React, we should set the role attribute of the a element.

Categories
React Answers

How to make a scrollable div to stick to bottom, when outer div changes in size in React?

Sometimes, we want to make a scrollable div to stick to bottom, when outer div changes in size in React.

In this article, we’ll look at how to make a scrollable div to stick to bottom, when outer div changes in size in React.

How to make a scrollable div to stick to bottom, when outer div changes in size in React?

To make a scrollable div to stick to bottom, when outer div changes in size in React, we can use flexbox.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        height: "300px"
      }}
    >
      <div style={{ flexGrow: 0 }}>foo</div>
      <div
        style={{
          flexGrow: 1,
          overflowY: "auto",
          alignItems: "center",
          display: "flex"
        }}
      >
        bar
      </div>
      <div style={{ flexGrow: 0 }}>baz</div>
      <div></div>
    </div>
  );
}

We make a flex container by setting the display CSS property to 'flex', flexDirection to 'column' and a height for the flex container.

Then we add the elements inside the flex container.

We make the bottom div stick to bottom by setting flexGrow of the div above the bottom one to 1 to make it fill the space.

And we set flexGrow of the bottom div to 0 so that it won’t stretch.

Conclusion

To make a scrollable div to stick to bottom, when outer div changes in size in React, we can use flexbox.