Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do conditional rendering according to screen width in react?

there is a problem, I don't know how to implement the component technically correctly. I want to do conditional rendering of an element depending on the device screen. Example: if the screen is less than 700 px then I make one conclusion, if more then the second

if(window.innerWidth > 700) {
   return(
    <Content>
       1 
    </Content>)
};
return (
<Content>
       2
</Content>)

I use react, next js, and typeScript technologies

how to do this?

like image 395
Евгений Морозов Avatar asked Oct 31 '25 11:10

Евгений Морозов


1 Answers

Create a width state in your component, and update state on window resize event, like this:

const App = () => {
  const [width, setWidth] = React.useState(window.innerWidth);
  const breakpoint = 700;
  React.useEffect(() => {
   const handleResizeWindow = () => setWidth(window.innerWidth);
    // subscribe to window resize event "onComponentDidMount"
    window.addEventListener("resize", handleResizeWindow);
    return () => {
      // unsubscribe "onComponentDestroy"
      window.removeEventListener("resize", handleResizeWindow);
    };
  }, []);
  if (width > breakpoint) {
    return (
      <div>
        <h3>Component 1</h3>
        <p>Current width is {width} px</p>
      </div>
    );
  }
  return (
    <div>
      <h3>Component 2</h3>
      <p>Current width is {width} px</p>
    </div>
  );
}


class Root extends React.Component {
  render() {
    return (
      <App/>
    );
  }
}

ReactDOM.render(<Root />, document.getElementById('root'));
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<div id="root">
</div>
like image 66
glinda93 Avatar answered Nov 03 '25 01:11

glinda93



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!