Home > Back-end >  Render div with state only on phones
Render div with state only on phones

Time:12-13

is there some way how to render div conditionally with state but only for mobiles? I have show more button, but i need it only for phone resolution, also I need to display that div with className text every time on desktop

const ListItem = ({ text }) => {
    let [showMore, setShowMore] = useState(false);

    return (
        <div className="item">
            <div>
                <div className={`text ${showMore ? "active" : ""}`}>{text}</div>
            </div>
            <button onClick={() => setShowMore((s) => !s)}>Show more</button>
        </div>
    );
};

CodePudding user response:

You can either use pure CSS or use a hook for media query like the following:

import {useMediaQuery, useMediaQueries} from '@react-hook/media-query'
 
// Using a single media query
const Component = () => {
  const matches = useMediaQuery('only screen and (min-width: 400px)')
  return `Matches? ${matches ? 'Matched!' : 'Nope :(')}`
}
 
// Using multiple media queries
const Component = () => {
  const {matches, matchesAny, matchesAll} = useMediaQueries({
    screen: 'screen',
    width: '(min-width: 400px)'
  })
 
  return (
    <div>
      Screen matched? {matches.screen ? 'Yes' : 'No'}
      Width matched? {matches.width ? 'Yes' : 'No'}
      All matched? {matchesAll ? 'Yes' : 'No'}
      Any matched? {matchesAny ? 'Yes' : 'No'}
    </div>
  )
}
import {useMediaQuery, useMediaQueries} from '@react-hook/media-query'
  
// Using multiple media queries
const Component = () => {
  const {matches, matchesAny, matchesAll} = useMediaQueries({
    screen: 'screen',
    width: '(max-width: 767px)'
  })
 
  return (
    {matches.screen ? (<div>Display on mobile</div>) : ''}
  )
}

Note that this solution is dependent on this addon

CodePudding user response:

you can set the active class in the media query.

At first, you can this div display none. when your resolution is phone then you set display block.

.active{
        display: none;
    }

    @media screen and(max-widht: '400px') {
       .active{
            display: block;
       }
    }
  • Related