I've been playing around with react-responsive to understand how to make websites mobile-friendly. Essentially, what I want to do is pass in a value from a function that tests whether a viewing screen is sized like a mobile phone. Practically stolen from the documentation of react-responsive, I have a function in a file called Mobile.js as follows:
const Mobile = () => {
const mobile = useMediaQuery({ query: '(max-width: 1000px)' })
return (
<div>
{mobile && <p>You are sized like a mobile phone</p>}
</div>
);
}
However, what I want to be able to do is pass the boolean "mobile" into other classes in other js files where I can then use different CSS classNames depending on the value of this boolean.
I have 3 specific questions.
How would I return the boolean mobile from the Mobile function to be used?
How would I access this returned boolean?
How would I change the className of a div depending on the value of this boolean?
Pretty new to web development (especially React) and these questions seem super simple and easy to solve, but for some reason, I just can't seem to figure it out by my own online research. Would love direct help and also some resources where I could learn more. Thank you so much!
To me, in a perfect world, the right code would look like this in my mind. Not sure how far off I am, but I was hoping maybe this could be of some guidance as to how I'm thinking.
In the function file,
// FILE Mobile.js
const Mobile = () => {
const mobile = useMediaQuery({ query: '(max-width: 1000px)' })
return (
{ mobile } // how to return a value?
);
}
export default Mobile;
In another file,
// FILE OtherClass.js
import Mobile from './Mobile';
class OtherClass extends Component {
constructor(props) {
super(props);
this.state = { mobile: <Mobile /> } // how to access the returned value?
}
render() {
return (
<div>
{this.state.mobile && <div className="text-mobile">} // how to change the className depending on value?
{!this.state.mobile && <div className="text-desktop">}
blah blah blah blah blah
</div>
</div>
);
}
}