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

Fontawesome is unable to update the class due to the presence of invalid characters in the string

const toggleDarkOrLight = document.getElementsByTagName('i')[0]; var toggled = false; const toggleFunction = () => { if (toggled === false) { toggleDarkOrLight.classList.remove('fa fa-toggle-off'); toggleDarkOrLight.classLi ...

Implementing a click event listener on an iframe that has been dynamically generated within another iframe

Below is the code I used to attach a click event to an iframe: $("#myframe").load(function() { $(this.contentWindow.document).on('click', function() { alert("It's working properly"); }); }) Everything seems to be working co ...

Can anyone provide guidance on incorporating lodash into an Ionic 2 project?

Recently, I began diving into a new project that involves Ionic 2. TypeScript is still fairly new to me, and I've been brainstorming ways to integrate lodash into my project. Have any of you tackled this before and can offer guidance on how to achiev ...

Mastering the art of maximizing efficiency with the Jquery Chosen Plugin

Currently, I'm facing an issue with the jQuery chosen plugin due to my large datasets causing the select box to hang and slow down. Below is my implementation of the plugin: var request = $.ajax({ method: "POST", url: "ajaxRequest.php", d ...

Setting the Montserrat Google font for the entire NextJS application that utilizes MUI components

Recently, I've been attempting to integrate the Montserrat font into my Next.js application. Despite my efforts, when inspecting the text in the browser, the font family consistently shows up as Roboto along with the same set of fallbacks. "Roboto", ...

Storing user data in node.js using the express-sessionTo save user data in

Using express and express-session with mysql on nodeJS has been successful for me. I managed to set up a cookie and session as well. Take a look at my code: app.use(cookieParser('3CCC4ACD-6ED1-4844-9217-82131BDCB239')); session({resave: true, s ...

Using jQuery's .load function to load an HTML file from a href attribute into a div element may not function as

I'm struggling to populate the href section of my dropdown menu with my files. I'm attempting to dynamically load the files in the .where-you-tune class. Something must be off because I keep encountering (index):81 Uncaught TypeError: $(...). ...

Error occurred while attempting to access querystring values

Is there a reason why 2 out of the 3 querystring parameters have values, while one is undefined? <li class="@ViewBag.ShowNext">@Html.RouteLink("Next »", "Search", new { page = @ViewBag.NextPage, q = @ViewBag.TextClean, Option = @ViewBag.Option }, n ...

Removing text that was added via the chart renderer in Highcharts can be accomplished by identifying the specific element

Instead of using a legend in my graph, I have added labels directly to the series (view example here). After drawing the graph with these labels attached, the user can click a button to add another series which hides some existing lines successfully. Howev ...

Injection of environmental variables into app services

Through the use of Nx, I have created multiple apps that each have their own environment with different API URLs. The Nx Workspace library includes shared services that are utilized among all apps, however, it is necessary to pass the environment-api-url w ...

The issue of array sorting, specifically the function(a, b) {return b.value - a.value), is causing some

I am struggling to retrieve data from firebase and sort them according to the field 'overallScore' in descending order. Despite following suggestions like using array.sort(function(a, b) {return b.value - a.value), I have not been successful in s ...

The issue with loading scripts in a ReactJS NextJS app is related to the inline condition not working

I'm having trouble with an inline condition for loading scripts. The condition seems to be working because the tag is displaying text, but when it comes to scripts, it doesn't work. How can I resolve this issue? const cookie = new Cookies().get ...

What steps should I take to resolve the NextRouter "not mounted" error when deploying my Next JS 13 app on Vercel

I am encountering an issue while deploying my Next.js 13 app. The error message states: Module not found: Can't resolve 'encoding' in '/vercel/path0/node_modules/node-fetch/lib' Additionally, I am facing a "Next Router not mounte ...

The server appears to be up and running, however there seems to be an issue when attempting to access the API as it is returning an Error: connect ECONNREFUSED 127.0.0.1

Trying to decouple app and server. Successfully running, but encountering Error: connect ECONNREFUSED 127.0.0.1:3000 in Postman when hitting "app.get('/')" API despite making necessary changes. In ./routes/users.js const express = requ ...

In Angular, use the ngFor directive to iterate through items in a collection and add a character to each item except

Currently, I am iterating through my data list and displaying it in the view using spans: <span *ngFor="let d of myData"> {{d.name}}, </span> As shown above, I am adding a comma ',' at the end of each item to ensure a coherent displ ...

Troubleshooting problem with toggling menu in ReactJS using Material UI

I've been working on a feature that involves toggling the open state of a menu using both a button and menu items. However, I'm facing an issue where the menu expands when clicked but doesn't close upon a second click. class Topbar extends R ...

Merging Promises in Typescript

In summary, my question is whether using a union type inside and outside of generics creates a different type. As I develop an API server with Express and TypeScript, I have created a wrapper function to handle the return type formation. This wrapper fun ...

behind the scenes of a disappearing bootstrap modal

Greetings everyone! Currently, I am deep into the process of identifying and resolving a pesky bug that has been impacting my work. The project in question involves developing a module for an open-source platform built on Laravel and Bootstrap - Microweb ...

Guide to adjusting margin size according to specific screen size thresholds?

I've set up a series of reactstrap cards that are dynamically organized into rows. On "md" screen sizes and larger (bootstrap), there will be 3 cards per row, while fewer screens will display 2 cards. Here's the component: <Card outline ...

Encountered an error stating 'Cannot read property 'user' of undefined' while attempting to generate a user document during account creation using Firebase

I'm having trouble adding the user ID to a new collection named 'accounts' during account creation. I keep encountering an error that says 'Cannot read property 'user' of undefined'. Can someone please help me troubleshoo ...