How to deselect a checkbox in next.js when another one is selected

I'm looking to create a navigation system where clicking on a button scrolls to a specific section. However, I'm wondering how to deselect three inputs when one is selected in next.js using the code below. Do I need to modify each menu item individually or can I keep it as is?

Any help would be greatly appreciated :)

function NavMenu() {
    
    function MenuItem(props) {
        const [menuItemActive, setMenuItemActive] = useState(false);

        const MenuItemToggle = ({onChange, value}) => 
            <label className='navitem-container'>
                <input checked={value} type="checkbox" onChange={onChange} className='menuiteminput' id={props.idinput}/>
                <span className='navitem-slider' id={props.idspan}>
                    {props.children}
                </span>
            </label>
        ;

        return (
            <div>
                <MenuItemToggle value={menuItemActive} onChange={(event) => setMenuItemActive(event.currentTarget.checked)}/>
            </div>
        )
    }


    return (
        <div>
            
            <div className='left-nav'>
                <div className='left-navitem-container'>
                    <MenuItem idspan="services-span" idinput="services-input">
                        Services
                    </MenuItem>
                    <MenuItem idspan="portfolio-span" idinput="portfolio-input">
                        Portfolio
                    </MenuItem>
                    <MenuItem idspan="about-us-span" idinput="about-us-input">
                        About Us
                    </MenuItem>
                    <MenuItem idspan="contact-span" idinput="contact-input">
                        Contact
                    </MenuItem>
                </div>
            </div>
        </div>
    )
}

Below is the corresponding CSS:

.left-nav {
  width: 250px;
  height: 100vh;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding-left: 3%;
  position: fixed;
}

.menuiteminput {
  position: absolute;
  left: -9999px;
  top: -9999px;
}

.menuiteminput:checked + #services-span:before,
.menuiteminput:checked + #portfolio-span:before,
.menuiteminput:checked + #about-us-span:before,
.menuiteminput:checked + #contact-span:before {
  left: 72px;
  content: url(../public/svgs/blank.svg);
  transition-duration: 0.5s;
}

.menuiteminput:checked + .navitem-slider {
  padding-left: 13px;
}

.navitem-container {
  height: 30px;
  display: flex;
  align-items: center;
  margin: 30px 0;
}

.navitem-slider {
  margin: 20px 0;
  height: 30px;
  background-color: var(--accent-color);
  width: 100px;
  display: flex;
  align-items: center;
  font-size: 10pt;
  border-radius: 100px;
  position: relative;
  padding-left: 33px;
  cursor: pointer;
  transition-duration: 0.5s;
}

.navitem-slider:before {
  width: 16.5px;
  height: 16.5px;
  border-radius: 100px;
  background-color: white;
  left: 3px;
  position: absolute;
  top: 3px;
  padding: 4px;
  transition-duration: 0.5s;
}

#services-span:before {
  content: url(../public/svgs/service.svg);
  transition-duration: 0.5s;
}

#portfolio-span:before {
  content: url(../public/svgs/portfolio.svg);
  transition-duration: 0.5s;
}

#about-us-span:before {
  content: url(../public/svgs/team.svg);
  transition-duration: 0.5s;
}

#contact-span:before {
  content: url(../public/svgs/contacts.svg);
  transition-duration: 0.5s;
}

Thank you in advance for your assistance :D

Answer №1

To have control over the status of all checkboxes, you can implement a shared state in the NavMenu component as shown below:

If you want to learn more about this technique, check out: Controlled and uncontrolled field and lifting-state-up


function MenuItem(props) { 
    return (
       <div>
           <label className='navitem-container'>
              <input checked={props.checked} type="checkbox" onChange={props.onChange} className='menuiteminput' id={props.idinput}/>
               <span className='navitem-slider' id={props.idspan}>
                    {props.children}
                </span>
            </label>
        </div>
      )
}

function NavMenu() {
    const [activeItem, setActiveItem] = React.useState('');
      
    const handleChange = (e)=> {
      const {id, checked} = e.target;
      setActiveItem(checked ? id : '');
    }  
    
    return (
        <div>
            <div className='left-nav'>
                <div className='left-navitem-container'>
                    <MenuItem idspan="services-span" idinput="services-input" checked={activeItem == "services-input"} onChange={handleChange}>
                        Services
                    </MenuItem>
                    <MenuItem idspan="portfolio-span" idinput="portfolio-input" checked={activeItem == "portfolio-input"} onChange={handleChange}>
                        Portfolio
                    </MenuItem>
                    <MenuItem idspan="about-us-span" idinput="about-us-input" checked={activeItem == "about-us-input"} onChange={handleChange}>
                        About Us
                    </MenuItem>
                    <MenuItem idspan="contact-span" idinput="contact-input" checked={activeItem == "contact-input"} onChange={handleChange}>
                        Contact
                    </MenuItem>
                </div>
            </div>
        </div>
    )
}

ReactDOM.render(<NavMenu/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

<div id="root"></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

What is the most effective method for updating the data in an Angular UI-Grid? Is it better to refresh the state or replace the data in $scope

I am using an Angular UI grid on my page. Whenever a user double clicks on a row, a modal pops up displaying the row data for updating. After a successful update, I need to display the latest data in the UI grid. To achieve this, I have two options: U ...

The && operator is not executed when the button is disabled

There is a button on the page that has been disabled using the [disabled] property. <button class="btn btn-primary center-block" (click)="sign(sf.value)" [disabled]="validateInsuredFirstName(firstName.value) && validateInsuredLastName(l ...

Having trouble with a JavaScript Promise that seems to be stuck in limbo

I have developed two custom promises that are quite similar, with the only difference being that they operate on distinct user inputs. Both promises utilize various classes and methods from Google Maps API v-3. What's puzzling is that when the first ...

The application is not supported by the Django Heroku buildpack

Even though I am using the heroku/python buildpack, it still says my app is not compatible. As a beginner in Django, I could really use some help with this issue. Here is the build log: -----> Building on the Heroku-20 stack -----> Using buildpack: ...

Combining PageObjects with non-angular pages: is it possible?

I am currently working on writing protractor tests for our application. One specific challenge I have encountered is dealing with a non-angular page within an angular page as an iframe. The issue I am facing is that I cannot properly map fields from the n ...

When running the test, the message "Unable to resolve all parameters for BackendService" is displayed

Upon executing the ng test command, the following error was displayed. This is my service specification: describe('BackendService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { p ...

Exploring jQuery's capabilities with Cross-Domain URLs

I created a basic index.php file with the following code: <!DOCTYPE html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/httpGet.js"></script> <script type ...

The Express server's `GET` request at the root does not seem

When I access localhost:8080/chat?k=1&d=1, the console displays "CHAT PAGE" and everything works correctly. However, when I try to visit localhost:8080, the root event does not display "INDEX PAGE" as expected. Instead, it automatically retrieves ind ...

Functional Components with Methods in ReactJS

When creating a functional stateless component that requires methods to access props, is there a recommended approach or best practice to follow? For instance: function Stateless(props) { function doSomething(props) { console.log(props); } ...

Is there a way to extract values from a particular object?

Currently, I am utilizing a JSON server to establish a straightforward login system. The data stored on the server is structured as follows: { "users": [ { "name": "user1", "password": "pass1", "email": "<a href="/cdn-cgi/l/emai ...

Contrasting WebSQL and SQLite in terms of their utility in mobile applications and web browsers

Could you confirm if WebSQL and SQLite are the same? Are both WebSQL and SQLite available in PhoneGap? Will the JavaScript code used for WebSQL in a web browser be the same for a mobile app, or will we need different code? What advantages does WebSQL ha ...

how to create a smooth transition back to the original state after a click event

I've put in a lot of effort to make sure my code for the DECAY shapes is correct up to this point. The click event I implemented makes the shapes gradually start being affected, just as I intended. However, once I release the mouse or finger, it insta ...

Is there a way to still access the data from a radio button even if it hasn't been selected?

I'm currently working on a questionnaire feature and facing an issue where I need to capture all answers, even if the radio button is not checked. Here's a snippet of the HTML code: $('input:radio').each(function () { if ($(this). ...

Has makeStyles caused IconButton hover color not changing in MUI anymore?

Greetings, I have been searching for a way to modify the hover color of an IconButton. Unfortunately, the previously discovered solution no longer appears to be effective Here is my current progress in this Code-Sandbox ...

What is the best method for customizing icons in Material UI DataGrid?

We are struggling to customize the icons used in the DataGrid component from Material UI. Despite the limited documentation available, we are unable to find a clear way to achieve this. While the documentation mentions slots for icons, it lacks explanatio ...

Differences between addEventListener and jQuery's on method, as well as form.submit and jQuery's

I encountered a situation where callbacks registered using jQuery's on method were not being called when trying to trigger form submission with the HTML Form element object instead of jQuery. After some testing, I discovered that changing the code to ...

Building a DOM element using jQuery

I have a function $(document).ready(function () { $("#btnhighlight").click(function () { var htext = $("#txthighlighttext").val(); $("#lstCodelist option").each(function () { var sp = $(this).text(); ...

Implementing React hooks to efficiently remove multiple items from an array and update the state

Looking for help on deleting multiple items from an array and updating the state. I have selected multiple items using checkboxes, which are [5, 4, 3]. My goal is to remove all these items from the array based on their ids and then update the state accordi ...

Creating a callback function within its own definition

I need help with my download function that is calling a callback to "downloadCallback". Is it possible to define the downloadCallback function inside the download function itself? If so, how can I achieve this? Below is the implementation of the download ...

The combination of setInterval() and if(confirm()) is not possible in pure JavaScript

One day, I encountered a simple if(confirm()) condition like this: if(confirm('Some question')) { agreed_function(); } else { cancel_function(); } function agreed_function() { console.log('OK'); } function cancel_function( ...