React validation functionalities

Incorporating React, I am attempting to implement a validation feature within a footer containing multiple buttons with unique values such as home, orders, payments and more. My goal is to dynamically display an active state for the button corresponding to the current location (handled in CSS). However, I am struggling with setting the correct setState method to achieve this.

interface State {
  value: any,
  isActive: boolean
}

class Footer extends React.PureComponent<Props, State>{
  state: State = {
    value: '',
    isActive: false
  }

  render() {
    const { isActive } = this.state
    return (
      <IonFooter>
        <div className="footer-menu-home">
          <button value="home" onClick={() => this.props.history.push('/home')}>
            {isActive && (<div>
                <img src={iconHomeActive} alt="" />
              </div>
            )}
            {!isActive && (
              <div>
                <img src={iconHomeInactive} alt="" />
              </div>
            )}
          ...
         </button> 
         <button onClick={() =>this.props.history.push('/orders')} >
              <div>
                <img src={iconOrderInactive} alt="" />
              </div>
              Orders
          </button>
        </div>
      </IonFooter>    
    );
  }
}

Essentially, I aim to visually distinguish the active button based on the user's current selection. However, I am unsure of how to strategize this behavior or specify the target property when selecting the 'orders' option using a button press.

Answer №1

Important: It seems like you are utilizing a routing library in your project. I suggest making full use of it to determine if the current link is active or not. You can refer to this article for more information: https://medium.com/swlh/using-react-router-navlink-to-specify-the-active-element-in-a-navigation-bar-38700ffd4900

However, achieving the same functionality without utilizing the routing library is also possible:

// checking if the state/button value matches the route pathname
const isActive = this.props.history.location.pathname.split('/')[1] === this.state.value 

// updating value in button click handler
handleButtonClick = (value) => () => {
  this.setState({
    value
  }, () => {
    this.props.history.push(`/${value}`)
  })
}
<button onClick={handleButtonClick('home')} />

// rendering conditionally based on isActive
{isActive ? (
    <img src={iconHomeActive} alt="" />
) : (
    <img src={iconHomeInactive} alt="" />
)}

Additional Update: Ques: Can the function be modified to pass the value through the button label? For example, value: "home"

You can utilize event to access the properties of the button element as shown below

  handleButtonClick = (event) => {
    const value = event.target.value;
    // similarly const name = event.target.name;
    this.setState({
      value
    }, () => {
      this.props.history.push(`/${value}`)
    })
  }

Ques: If you want to add a className = "active", how can you conditionally show or hide the active state?

<button className={!!isActive && 'active'} onClick={handleButtonClick} />

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

Using a static value in the comparator is necessary for Array.find to function properly in Typescript

Looking to retrieve an item from an array: const device = this.selectedDevtype.devices.find(item => console.log(this.deviceID); return item.device_id === this.deviceID; }); console.log(device); When this.deviceID is logged, it shows "4", but t ...

Leveraging Typescript's robust type system to develop highly specific filter functions

I'm attempting to utilize the robust TypeScript type system in order to construct a highly typed 'filter' function that works on a collection (not just a simple array). Below is an illustration of what I am striving for: type ClassNames = &a ...

Getting around using Material-UI Icons

Is it possible to utilize a Material-UI Icon for navigation using React Router Dom? I attempted the following approach without success: <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon> With buttons, I am able to use component={Link ...

Error message: NextJs throws aReferenceError when trying to access the document object on page refresh

encountered the error ReferenceError: document is not defined when attempting to refresh the page I am working on creating a component using react-quill and then calling that component within a page. This is my component : import React, { useState } from ...

Recommendations for organizing code with respect to models in Angular using TypeScript

Within my C# backend, I structure my entities and entity lists using classes. Any needed functions or methods are simply added to the corresponding class. On the contrary, in Angular/TypeScript examples, models are typically defined as interfaces. This ra ...

Enhancing my code by implementing various conditions in React

Looking for ways to enhance my code quality (Very Important, Important, Medium, Low, Good, Excellent,...) : { Header: "Opinion", accessor: (row) => row.opinion, Cell: props => <span> {props.value == ...

Place the cursor at the conclusion of the text box

I am working on creating a user input form for chat messaging and I need some help. Here is the HTML-code snippet that I am currently using: HTML-code Currently, when the user presses ENTER, I retrieve the text from the textbox and save it. If the user ...

Can a native thread be created for PWAs in order to access Geolocation data even when the browser is closed?

Seeking a solution for my Progressive Web App that requires continuous updates of the user's location. Service workers lack access to the navigation.geolocation object, and my current workaround with a React Component halts when the browser is closed ...

Tips for accurately extracting values from a decoded JSON

Hello, I am posting this query because I recently encountered an issue with json encoding in PHP. When using the json_encode() function, my original JSON data gets converted to strings instead of maintaining its original variable type. For instance, let&a ...

Issue with saving date values accurately in Nestjs/Prisma

After logging the response body before saving it to the database, I noticed that the shape is correct. Here's what it looks like: //console.log response body CreateOpenHourDto { day: 'WEDNESDAY', startTime: 1663858800000, endTime: 16638786 ...

Discovering child elements within an iframe using Angular and customizing their appearance

Is there a simple and effective way to locate child nodes within an iframe using Angular in order to access the HTML element? Currently, I have implemented the following method: I designated a reference variable within my iframe (#privacyPolicy) <ifra ...

Navigate through collections of objects containing sub-collections of more objects

The backend is sending an object that contains an array of objects, which in turn contain more arrays of objects, creating a tree structure. I need a way to navigate between these objects by following the array and then back again. What would be the most ...

WebStorm is not auto-completing the Emotion Styled Components

While using @emotion/styled in WebStorm, I have noticed that there is no Intellisense for autocomplete within my style object. However, Typescript does seem to be checking to some extent: const StepTimer = styled.button({ borderRadius: 50, height: &ap ...

What is the method for retrieving all documents that contain an array field with at least one object-element having a property value of 'X'?

I have a collection of MongoDB documents structured like this: { "group": "P32666", "order": [{ "_id": { "$oid": "5e8e9b40e7999f6b90fd88bf" }, "name": "Dmitriy A", "login": "example", "password": "example", "email": "exampl ...

typescript api overlooking the async await functionality

My controller contains an asynchronous method that is supposed to set a results object. However, I'm facing an issue where instead of waiting for the 'await' to finish executing, the code jumps to the response object call prematurely, leavin ...

Custom Joi middleware in Express v4 is failing to pass the Request, Response, and Next objects

I am currently in the process of developing a unique middleware function to work with Joi that will be placed on my routes for validating a Joi schema. In the past, I have created middlewares for JWT validation without passing any parameters, and they wor ...

Sending JSON object data to an API endpoint using the POST method in an Angular application

Attempted to post data to an API, but received a 400 bad request error. After testing with Postman, it seems that the issue may lie within my service or TypeScript code. As a newcomer to Angular, I am seeking assistance as I have searched extensively witho ...

Implement a call feature using ReactJS

My service method involves making a PUT call to an API with an ID parameter. However, I am facing issues with hitting the .put URL. Can someone please verify if this is the correct approach? ENDPOINTS = { SAMPLE: "/sample", }; Below is my ...

Modifying the appearance of a Component within a NavLink

I'm currently working on a navbar using NavLink from React-Router-Dom. It's fine to use the 'isActive' prop to style the active Link, but I'm stuck on how to style the subelements inside it. For more specific details, please take a ...

Tips for retrieving input values when they are not available in HTML documents

In this code snippet, I am creating an input element with the file type without adding it to the DOM. My goal is to retrieve the value of this input once the user selects a file. Even though the input is not part of the HTML template, I still want to acces ...