What steps can be taken to avoid generating a fresh instance of a component when rearranging them?

On the desktop version, the component is structured like this:

  <div className="parent-comp">
    <div id="child-1" />
    <div id="child-2" />
  </div>

However, on the mobile version, it switches to:

  <div className="parent-comp">
    <div id="child-2" />
    <div id="child-1" />
  </div>

Is there a way to avoid having to recreate child-1 and child-2 each time the screen size changes from mobile to desktop?

Answer №1

To tackle the issue of storing idNum and dynamically setting it based on screen size, you can create a state for idNum and write a function to determine the proper value for it. The following solution attempts to address this problem:

const [idNum, setIdNum] = useState(1);
    const handleResize = () => {
        if (window.innerWidth > 960) {
            setIdNum(1);
        } else {
            setIdNum(2);
        }
    };
    useEffect(() => {
        handleResize();
    });
    window.addEventListener('resize', handleResize);
    return (
        <div className="parent-comp">
            <div id={`child-${idNum}`} />
            <div id={`child-${idNum === 1 ? 2 : 1}`} />
        </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

Tips for incorporating adjustable export dimensions for Highcharts within Next.js or React.js

Currently, I'm tackling a project that involves Next.js and Highcharts. One of the requirements is to allow users to export charts in different sizes - small, medium, and large. Is there a way to make this work seamlessly? menuItems: [ ...

The enigmatic "margin-30" element within adaptable layout design

Recently, I decided to challenge myself by learning pure CSS and moving away from relying on Bootstrap for my layouts. The only aspect of Bootstrap I really used was the container class, so I created a basic project to experiment with pure CSS. In this pro ...

Initiating a stealthy phone call without any visible queues

Is it possible to have an application in Android that can run a recorder or make a phone call in the background without showing it to the user, and automatically end after a set timer? ...

Tips for changing the color of a column in a mui table

I’m struggling with coloring specific columns in a mui table. How can I color a column, let's say green? I want to color the name column based on the data provided below. If the column name matches 'name', what should I do while iterating ...

Retrieve new data upon each screen entry

After running a query and rendering items via the UserList component, I use a button in the UserList to run a mutation for deleting an item. The components are linked, so passing the deleteContact function and using refetch() within it ensures that when a ...

What is the process of initializing divs in DataTables?

My application has a DataTable installed, but I encountered an error message stating "DataTables warning: Non-table node initialisation (DIV). For more details about this error, please visit http://datatables.net/tn/2". I'm aware that DataTables is d ...

Initiating the ngOnInit lifecycle hook in child components within Angular

I am facing an issue with controlling the behavior of child components in my Angular application. The problem arises when switching between different labels, causing the ngOnInit lifecycle hook of the children components not to trigger. The main component ...

Is there a way to incorporate a base64 encoded image from a text file into an HTML image?

I have several images stored as base64 blobs in a remote location. Let's focus on one specific image: llorkcir.txt data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxISEhASEBAQDxAQDw8QEA8PEA8PDw0PFRIWFhURFRUYHSggGBolGxUVITEhJSkrLi4uFx8zODMt ...

Is it possible to create a CSS-only negative border radius?

I'm reaching out for help with a specific issue. I want to create a unique negative border radius for my navigation links, similar to the design shown in this image: http://prntscr.com/9vi0b5 Instead of using images like in the example, I'm look ...

Enhancing vanilla HTML elements with custom props using React

const handleSelectChange = (e) => { console.log(e.target.getAttribute('id')); }; return ( <div> <select onChange={(e) => handleSelectChange(e)}> <option value="1-10" id=&qu ...

Tips on presenting our data using JSON structure

Hey there! I'm new to Next JS and I'm looking to showcase the data from my index.js file in JSON format in my dynamicid.js file. Can anyone guide me on how to achieve this? index.js In my index.js file, I currently display my output but now I ...

Enhancing functionality through interactive buttons: optimizing the performance of this dynamic data code

I am seeking a more efficient way to retrieve names from a database using PHP and MySQL. Currently, I have multiple if isset statements in my code, one for each button that retrieves a specific name. Is there a better approach to achieve the same result ...

Incorporating HTML into the Ajax Response

I recently encountered a strange issue with a service that returns an HTML page as the AJAX response. This page contains a form that is automatically triggered by scripts within the page, resulting in a POST request being sent when the page is rendered. My ...

The styled component is not reflecting the specified theme

I have a suspicion that the CSS transition from my Theme is not being applied to a styled component wrapped in another function, but I can't pinpoint the exact reason. I obtained the Basic MUI Dashboard theme from this source and here. Initially, inte ...

Is Java Cryptography truly as challenging as it seems?

Recently, I've been working on creating an application that allows for encryption and decryption of text files while also enabling the transfer of keys and files between machines. My goal is to expand my Java skills, but I'm struggling to find us ...

Axios is retrieving an incorrect URL through Express

I am currently developing a MERN stack application that mimics Tinder's functionality. My backend server is hosted on localhost:8001, and the frontend is on localhost:3000. I have opted to use MongoDB for storing the data related to tinder cards. Be ...

The way in which notifications for updates are displayed on the Stack Overflow website

Could someone shed some light on how the real-time update messages on this platform are created? For instance, when I am composing a response to a question and a new answer is added, I receive a notification message at the top of the page. How is this fun ...

Selenium Chrome Driver allowing for sending key combinations to a window

I am looking to trigger a key press combination using the Selenium Chrome driver. This action does not involve sending text to a textbox or clicking on any buttons. My interest lies in executing commands like command+R (reload on Mac OS). Note that reload ...

Div failing to expand to fit its contents

I'm having trouble getting my info-container div to adjust its height based on its contents. I suspect that the floating div within it might be causing the issue, but I'm not certain. I've included a link to jsfiddle where you can view the C ...

The Glyphicon icon fails to appear on the initial page load and only shows up after refreshing the

I have been utilizing bootstrap.min.css from bootstrap v3.3.5 which I downloaded from http://getbootstrap.com and used it locally. However, I encountered an issue with glyphicons when running it on IE 9 and above. The glyphicon icon disappears on the first ...