In ReactJS, ensure only a single div is active at any given moment

I'm working on a layout with three divs in each row, and there are multiple rows. Only one div can be selected at a time within a row, and selecting a new div will automatically unselect the previously selected one. Here is a simplified version of my code:

 <div className="row">
    <div className="heil select"><button>Click One</button></div>
    <div className="heil"><button>Click Two</button></div>
    <div className="heil"><button>Click Three</button></div>
</div>
...

The select class is used to highlight the clicked div. I need help implementing this functionality dynamically in React, where only one div in each row can be selected (similar to a radio button). I'm new to ReactJS, so any guidance would be greatly appreciated. Thank you!

Answer №1

I have created a functional example that meets your requirements.

import { useState } from "react";

export default function Grid() {
    const numRows = 3;
    const rows = Array(numRows).fill(0);
    const cellsPerRow = ["Click One", "Click Two", "Click Three"];
    const [selectedCellIndexes, setSelectedCellIndexes] = useState(
        Array(numRows).fill(0)
    );

    const handleCellClick = (parentIdx, childIdx) => {
        setSelectedCellIndexes((selectedCellIndexes) => {
            selectedCellIndexes[parentIdx] = childIdx;
            return [...selectedCellIndexes];
        });
    };

    return (
        <div>
            {rows.map((row, parentIdx) => {
                return (
                    <div className="row">
                        {cellsPerRow.map((name, childIdx) => {
                            return (
                                <div
                                    className={`cell ${
                                        childIdx === selectedCellIndexes[parentIdx] && "highlighted"
                                    }`}
                                    onClick={() => handleCellClick(parentIdx, childIdx)}
                                >
                                    <button>{name}</button>
                                </div>
                            );
                        })}
                    </div>
                );
            })}
        </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

Struggling to handle JSON response in JavaScript

Upon receiving a JSON response from the Amazon API, here is how it appears: { "Result": { "Data": { "Title": "HALO 3 (XBOX 360 - REGION FREE)", "FormattedPrice": "$19.95", "Source": "Product Description", "Content": "The epi ...

Centering an image (svg) vertically inside a link tag

I've been struggling to vertically center the config button (#config) and none of the options I've tried worked the way I wanted. Here is a link to my CodePen: http://codepen.io/fenwil/pen/ONRXwz Here is the crucial part of the code that need ...

Arranging Content with Bootstrap Columns

I am trying to organize my content into three sections as follows: A - main content of page B - very important content (must be visible without scrolling) C - less important content. The current layout I have is like this: ----- |A|B| |A|C| ----- Howe ...

The Heroku application is rendering with different CSS and positioning compared to the local development environment

My locally hosted site has correct CSS and positioning, but once deployed to Heroku, it appears to lose some of its CSS styles. I am using the MERN Stack for this project. I suspect that the issue may be related to my node_modules, even though I have them ...

WARNING: Alert raised due to the discovery of two offspring sharing identical keys, `${item}-${index}`

I have been facing the issue of receiving an error message 'ERROR Warning: Encountered two children with the same key, ${item}-${index}' and I am not sure what is causing it. Can someone please guide me on how to resolve this problem? Any help w ...

Error: Cannot locate module: Vue not found, incorrect path specified

I am facing an issue with my webpack configuration. I have placed my webpack.config.js and node_modules in a subfolder. When attempting to run the command npm run build, I encounter the following error: ERROR in ../public/Vue/Components/Rating.vue Module n ...

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

Allow the button to be clicked only when both options from the 1/3 + 1/3 radio buttons are selected

How can I ensure that the next <button> at the bottom of the HTML is only clickable when at least one of each <input type="radio"> is checked? Also, how do I integrate this with my current function? The button itself triggers a jQuery function ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

differences in rendering of flexbox align-items: center between Chrome and Firefox

As I was attempting to center a div inside another div using flexbox, an inconsistency in rendering between Firefox and Chrome caught my attention. In the scenario, there are 3 divs, each with properties display:flex, justify-content:center, and align-ite ...

Communication between a directive controller and a service via an HTTP call

I'm currently developing an Angular directive that loads a Highchart.js area graph by passing some variables to it. Here's how I am using the directive: <andamento-fondo-area-chart color="#3FAE2A" url="../data.json"></andamento-fondo-a ...

Establish height and width parameters for creating a dynamic and adaptable bar chart with recharts

I am currently facing an issue with recharts while trying to implement a BarChart. The setting width={600} and height={300} is causing the Barchart to be fixed in size, rather than responsive. How can I make the BarChart responsive? I attempted using per ...

Angular 1: Handling Multiple Conditions and Exclusions Based on Other Conditions

I have currently added an additional span to accommodate one condition. <div ng-repeat="(key, resultLinks) in resultGroup.resultLinks"> <div ng-if="key < 4 || viewMore" ng-repeat="(subKey, linksWrap) in resultLinks.linksWrap"> & ...

React: Blur input element when escape key is pressed

I need help with a functionality for an input tag. When the escape key is pressed, I want the focus to be removed from the input element so that there is no text cursor or any styling related to focus (meaning user input will not be registered in the input ...

Custom AngularJS directive fails to reflect changes in model after selecting a file

I recently created a custom directive called ng-file-chosen, which is supposed to capture the selected file name from an <input> element and bind it to the ng-model passed in. In the code snippet below, the result of ng-file-chosen is linked to mode ...

The div background image in Vue.js is displaying a 404 not found error

I've encountered an issue while trying to set a background for a div. Strangely, when using the same relative path with an img tag everything works fine, but as soon as I try to achieve the same result with a div, I receive a 404 error. This img tag ...

Axios is not properly executing the post request

While attempting to submit data using axios in NodeJS and ReactJS, I encountered the following errors: Here is the code I used for posting: axios({ method: 'post', url: '/api/signup', data: { username: this.state. ...

Using jQuery, we can replace all `<span>` elements with `<img>` elements and then verify if the images have been successfully loaded

Similar Inquiry: jQuery check if image is loaded I find myself in a scenario where the following HTML structure is utilized: <div class="image"> <img class="" src="content-images/1.jpg"> <span class="slide" rel="content-images/ ...

The basic jQuery script seems to be malfunctioning

I am trying to attach an on click event to an li element using jQuery. I have written a simple jQuery code within the document ready function, but for some reason it is not functioning as expected. I have checked in both Chrome and Firefox, and there are n ...

javascript various backgrounds on click

I have implemented a list to allow users to select their top 3 choices, and I am using JavaScript to track these selections and change the background color accordingly. 1st selection -> Green background 2nd selection -> Yellow background 3rd sel ...