I'm using standard css3 and creating css files for each component and I am trying to decide on whether or not to use an event listener and multiple return functions inside of my react component. As apposed to writing out multiple media queries inside of my CSS file. Or alternatively using conditional classNames defined by useState to define a small, medium and large screen variable. That I could then use in my css file to keep the elements and their sizes written next to eachother. Instead of creating multiple css files, or Media queries.
I have a feeling with either method I run the risk of things becoming quite messy in the future with some screen sizes being updated as others aren't.
Is there a one size fits all solution I'm not seeing? Or do you think one of these methods is better than the next?
//What I have atm
const Comp = () => {
const [width, setWidth] = useState();
const [size, setSize] = useState('large');
useEffect(() => {
//add event handler...
//setStates
}, [states])
if(size === '') return {
<smallComponent/>
} else if (size === '') return {
<bigComponent/>
}
}
CodePudding user response:
It depends upon what you want to design.
- If you wish to automatically select components based on screen width/height, then media queries is the way to go. There is no point figuring out breakpoints in javascript.
- However, if at any given point of time you know what size of component to render, then pass the relevant information as props. For example
<Button size="small" />
<Button size="small" fullWidth />
For inspiration, do checkout how material-ui
is designed.
https://mui.com/material-ui/react-button
CodePudding user response:
Using media queries for responsive UI is best practice. If you use conditional rendering in order to differentiate UI by screen size, there will be a lot of rendering and thus, the quality of react application lowers. For better performance and better quality code, you should use media queries and it's more natural way to control UI by screen.