DEV Community

Cover image for How To Make A Responsive Component in React
Gloria Lim
Gloria Lim

Posted on

How To Make A Responsive Component in React

This is how useState and useEffect can be used to make a component responsive based on the window.innerWidth or the viewport width in React.

Final Result ✨

Final Product

In this example, the TextField component is imported from @mui/material.

Code ⌨

Here is my React component file which defines a React component named NewMemo, that renders a text area using the Material-UI TextField component.

What Is Going On❓

  • The useState hook initializes the windowWidth state with the initial window width minus 150 pixels (so that it does not take up 100% width of the screen).
  • The useEffect hook is used to add an event listener for the resize event on the window.
  • When the window is resized, the handleResize function is called, updating the windowWidth state.
  • A cleanup function is returned from the useEffect hook. This is to remove the event listener when the component is unmounted.
  • The empty dependency array ([ ]) means that the effect runs only once after the initial render.
  • The component returns a div with the class name "memo-textarea."
  • Inside the div, there is a TextField component from Material-UI.
  • The sx prop is used to apply custom styles to the TextField. Width is set dynamically based on the windowWidth state, and there's some margin.

Refresher - What Are Hooks💡

React Hooks are functions that allow functional components in React to manage state, lifecycle events and side effects.
They were introduces in React 16.8 as a way to enable stateful logic in functional components, which was only possible previously with class components.

TLDR - Rule of Hooks 🔱

There are a few rules to using Hooks to ensure consistent and correct usage of React Hooks. Just remember:

  1. Only Call Hooks at the Top Level of your React functional component.

  2. Only Call Hooks from React Functions.

  3. Do Not Call Hooks Conditionally.

  4. Always Call Hooks in the Same Order.

  5. Only Call Hooks from React Components or Custom Hooks.

Summary

The useState and useEffect hooks are two of the most commonly used React hooks. This was just one example of its application.

Media queries can also be used to build a responsive design. Let me know your thoughts!

Visit code repository

Top comments (0)