Issue with toggling in react js on mobile devices

Currently, I am working on making my design responsive. My approach involves displaying a basket when the div style is set to "block", and hiding it when the user browses on a mobile device by setting the display to "none". The user can then click on a button to open the basket.

The issue I am facing now is that the default state is set to true. This means that when a mobile user visits the website, they will see the basket first, which is not desirable. Ideally, I want the basket to be hidden when the user first visits, and they should need to click on a button to reveal it. However, setting the default state to false is not an option as desktop users won't be able to see the basket then.

// MY STATE
  const [toggle, setToggle] = useState(true);

<button onClick={() => setToggle(!toggle)}>Open</button>
<div
  className="box_order mobile_fixed"
  style={{ display: `${toggle ? "block" : "none"}` }}
  >
// BASKET CODE
</div>

Answer №1

To initially set the state value, consider using window.matchMedia.

By utilizing the Window interface's matchMedia() method, you can obtain a MediaQueryList object to check if the document conforms to a specific media query string and observe changes in its compliance.

Here's an example:

const [toggle, setToggle] = useState(window.matchMedia("max-width: 768px").matches);

Answer №2

By utilizing the media queries API, you have the ability to adjust the default value of toggle based on screen size. It's also important to listen for changes in screen size when necessary.

If you're interested, check out this resource: Media query syntax for Reactjs

Answer №3

Do you utilize tailwindcss? Check out this guide on how to integrate Tailwind into your project via CDN https://tailwindcss.com/docs/installation/play-cdn.

Rework your className to something like

${toggle ? "hidden" : "block"} sm:block
and eliminate the style property. On mobile view, the div will remain hidden. It will not be displayed as a block until the screen size hits 768 width or larger due to the media query sm:block. This setup ensures that the basket is only displayed after clicking the button. Ensure to follow this convention for your setToggle function:
setToggle(prevState => !prevState)
.

Answer №4

Ensure the initial state is set to false and implement the useState callback function

// STATE SETUP
  const [isActive, setIsActive] = useState(window.innerWidth > 700);

<button onClick={() => setIsActive(prevState => !prevState)}>Toggle</button>
<div
  className="box_order mobile_fixed"
  style={{ display: isActive ? "block" : "none" }}
  >
// ADDITIONAL CODE HERE
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying dynamic data with Vue.js and Chart.js

I am currently working on a VueJS code to display a bar-chart: Vue.component('bar-chart', { extends: VueChartJs.Bar, data: function () { return { datacollection: { labels: ['MICROFINANZAS -SECTOR C ...

How to adjust the size of the text on a button in jQuery mobile using custom

I am facing an issue with my jQuery mobile buttons that are placed inside a fieldset. Specifically, I need to adjust the font-size of one of the buttons. Despite attempting to add an inline style, it did not have the desired effect. Furthermore, I tried u ...

Is there a way to receive real-time updates from a Firestore document in ReactJS?

Having an issue with real-time updates: I'm working with a firestore document to display data on the screen. Everything works perfectly when retrieving and displaying the data initially. However, I am struggling to figure out how to get new data auto ...

Guide on incorporating d3 axis labels within <a> elements?

Issue at Hand: I am working with a specific scale var y = d3.scalePoint().domain(['a','b','c']).range([0,100]); I have successfully created an axis for this scale var y_axis = svg.append("g").attr("class", "axis").call(d3. ...

What causes Chrome to crash when dealing with lengthy tail files?

My objective is to display a log file in real-time using a websocket connection. However, I am facing performance issues with Chrome when the paragraph ('p') element in the HTML becomes large (about 450 lines). This is the current implementation ...

Provide solely the specified content range

While working with Node.js, my goal is to develop a video server that can serve a specific portion of a larger media file. Thanks to this gist, I have successfully created a video server and integrated it with an HTML5 video player using: <video contr ...

What is the best way to accomplish this using typescript/adonis?

While exploring some code examples on Bitbucket, I came across a sample that demonstrated how to paginate query results using JavaScript. However, as I attempted to apply it in my project, I encountered difficulties in declaring the types required for the ...

What is the best way to ensure that the text within Span children is properly laid out to match the width of the parent div tag?

This particular instance involves setting the width of the div tag to 200px and organizing all the span children to occupy the entire width of the parent div tag. If the first row is filled, the span tags should then flow into a second row. My attempt at ...

Tips for organizing CSS styles into common and unique statements

Is there a way to apply the same background style but different font styles to two elements without duplicating the style statement in the header part? ...

I'm working on a project that involves the FCC API, but I'm struggling to grasp the flow of the code

Having some trouble with my code and seeking help to understand what's going wrong. I want to avoid copying and pasting, but rather comprehend my actions. The issue arises when creating a new Url object in the post route. It seems like the function ge ...

Are we looking at a declaration of an arrow function? Is this concept even real?

I have been exploring the concept of function expressions versus function declarations with arrow functions. From my understanding, this is an example of an arrow function expression: const fred = greeting = () => { console.log("Hello from arrow ...

Troublesome glitches in jQuery?

I'm having an issue with the following code: var buggy_brand_name = ['Baby Jogger', 'Babyzen', 'Bugaboo', 'GB', 'Icandy', 'Joie', 'Maclaren', 'Mamas&Papas', 'Ma ...

Challenge involving CSS and Javascript for solving puzzles

In my attempt to create a puzzle with 2 rows and 3 columns using CSS and JavaScript, I envision the pieces of the puzzle being black and cut into various shapes. The objective is for users to drag these pieces onto the board in order to complete it. I have ...

Tips for creating a div that gracefully fades out its background image when hovered over, while keeping the internal content unaffected

I am looking to create a hover effect on a div element that has a background-color, background-image, and text. What I want is for the background-image to slowly disappear when the div is hovered over, while keeping the text and background color visible. I ...

Automatically append version number to requests to avoid browser caching with Gulp

When deploying my project, I utilize gulp to build the source files directly on the server. In order to avoid caching issues, a common practice is to add a unique number to the request URL as explained in this article: Preventing browser caching on web app ...

Why is my JSON object being mistakenly interpreted as a string literal during iteration?

I'm facing a seemingly simple question but I can't seem to figure it out. Below is the jQuery code I am working with: $(function() { $.get(urlGetContainerNumbers, function(data) { console.log(data); for (var idx = 0; idx &l ...

Steps on modifying the background of an element based on its location within the browser:

In the past, I've come across some impressive one-page websites with elements that would appear as you scroll. It seemed like they were created using just CSS. I think it might be achievable with the z-index and position properties? However, I can&ap ...

Can we enhance this JavaScript setup while still embracing the KISS principle (Keep it simple, Stupid)?

I have completed the following tasks: Ensured all event handlers are placed inside jQuery DOM ready to ensure that all events will only run Defined a var selector at the top of events for caching purposes Please refer to the comments below for what I be ...

The initial setting of [opened]="true" causes an issue with the Angular Material date range picker

Recently, we completed the upgrade of our app from Angular 14 to 15.2.9, which includes Angular Material. The migration process went smoothly, and now our app is compiling and running without any errors. However, we encountered an issue with the mat-date-r ...

Is it possible for Bootstrap to hide a grid column on extra small screens by setting its column width to zero?

Is there a specific Bootstrap class that allows me to hide a grid column for certain screen sizes without using media queries and the "display:none" style? ...