When a user clicks on the datepicker, I want to trigger a change in the

I am working on a Flight API and I need to implement functionality where when the user clicks on the return journey field, the button toggles from single trip to round trip (false to true).

<DatePicker
  hintText="Return Date"
  errorText={this.state.journeyDateErrorText}
  onChange={(event, value) => {                                                    
  this.setState({journeyDate: value})
  }}
  minDate={new Date()}      
  onClick={this.enableReturnDate.bind(this)}
  />

The above code shows my datepicker field. When the user clicks on it, I want to toggle the toggle component from false (single trip) to true (round trip).

<Toggle
 thumbSwitchedStyle={{backgroundColor: 'grey'}}
 onToggle={this.handleonToggle.bind(this)}
 label={this.state.tripType}
 defaultToggled={false}
 />

To achieve the desired result, I have added an onClick event that changes the state of the toggle, which is displayed as the label this.state.tripType.

enableReturnDate(e){

    this.setState({
        tripType: 'Round Trip'
    })
}

After adding the onClick event, the toggle state this.state.tripType changes from single trip to round trip. However, I also need to change the toggle button from false to true.

How can I accomplish this task?

Answer №1

It is important to manage the toggle component using state

<Toggle
     thumbSwitchedStyle={{backgroundColor: 'grey'}}
     onToggle={this.handleonToggle.bind(this)}
     label={this.state.tripType}
     defaultToggled={this.state.toggleState} // controlling toggle state through state
     />

    // Set toggle state to false initially, and then change it to true after datePicker interaction

enableReturnDate(e){
        this.setState({
            tripType: 'Round Trip',
            toggleState: true  //be sure to initialize the state as false in constructor
        })
    }

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

Clicking on the user will reveal a modal containing all of the user's detailed information

**I am trying to pass the correct user data to the modal ViewUser component, but it keeps displaying the same user regardless of which user I click on. How can I specify the specific user whose data should be shown? I am sending the user information as a ...

Exploring the new features of utilizing buttons with the onClick method in the updated nextJS version 14.1.3

"implement customer" import React, { useState } from "react"; import { FaChevronLeft, FaChevronRight } from "react-icons/fa"; export default function HeroSlider() { const images = [ "/images/homepage/home-1.jpeg&qu ...

React 17 Form not registering the final digit during onChange event

I am currently experiencing an issue with a form that includes an input field of type "number." When I enter a value, the last number seems to be skipped. For example: If I input 99 into the box, only 9 is saved. Similarly, when typing in 2523, only 252 ...

What are the steps to deploy a React, Next.js, and Express.js application on Netlify?

I am currently in the process of deploying my application to Netlify, featuring a combination of React, Next.js, and Express.js. While there are no errors showing up in the Netlify console, unfortunately, the site is not live as expected. https://i.stack ...

What is the best way to combine a React App and an Express App in order to deploy them as one

After successfully creating an Express and MongoDB API and connecting it to my React Application, I encountered a situation during deployment. It seems that I need to deploy both projects separately, which means I would need two hosting plans for them. H ...

Utilizing onClick to target data within a .map function

I am struggling with the code provided below: const test = (e) => { console.log('example:', e.target.item.attributes.dataIWant); } {records.map((item, index) => { return ( <> <Accordion key={index} ...

Develop a responsive image component with flexible dimensions in React

I am currently working on developing a dynamic image component that utilizes the material-ui CardMedia and is configured to accept specific height and width parameters. The code snippet I have is as follows: interface ImageDim extends StyledProps { wid ...

Ways to dynamically include onClick on a div in a react component based on certain conditions

Is it possible to conditionally set the onClick event on a div element in React based on the value of a property called canClick? Instead of directly checking this.state in the event handler, I am hoping to find a way to implement this logic within the re ...

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 ...

The importance of context visibility for functions in JavaScript within a React.js environment

Why is it that the react state is visible in the function handleFinishChange, but cannot be seen in validationFinishTime? Both are passed to the component InputFieldForm. When executing this code, an error of Uncaught TypeError: Cannot read property ' ...

How come the prop styling I applied to my React component child is not showing up?

I have successfully created a slider with icons using [mui slider][https://mui.com/material-ui/react-slider/]. The icons are added based on user preference through props. However, I am facing an issue where the 'fill: red' property is not renderi ...

Is it recommended that AJAX calls are placed on the server side?

As I work on my React/Express/Node application, I am facing a challenge with making AJAX requests to Instagram. Every time I attempt this, an error keeps popping up: No 'Access-Control-Allow-Origin' header is present on the requested resource. O ...

Navigating with React Router v6 beyond the confines of individual components

When using react-router v5, I would create the history object like this: import { createBrowserHistory } from "history"; export const history = createBrowserHistory(); Then I would pass it to the Router like so: import { Router, Switch, Route, Link } from ...

Navigate to the correct page when the Button is clicked in a ReactJS/Django project

Embarking on my web development journey, I opted for django/Reactjs to build a social network platform. I created several API methods like account/view_user/ to retrieve a list of users and account/view_user/ for specific user attributes. In React, I cra ...

Experimenting with Jest for pagination of tables in a React Material-UI component

Recently, I implemented a basic MUI data table with pagination from the following link: https://mui.com/material-ui/react-table/. The issue arose when trying to test it on the NEXT page using Jest. Whenever I attempted to change the row numbers from 5 to 1 ...

Creating a fresh React application to complement a pre-existing Express website

I have a unique website built with nodejs-express and ejs that consists of 5 main pages: home, events, about, developer, and gallery. All these pages are currently served using ejs. However, I am now faced with the challenge of integrating a web app create ...

What is the best way to renew a Firebase IdToken once it has expired?

I have set up my backend with express and am using the Firebase Admin SDK to send a token back to the client. Currently, the token expires after 1 hour. I noticed on Firebase that it's not possible to change the expiration property as users are suppos ...

issue with Firebase notifications not triggering in service worker for events (notification close and notification click)

I've been working on implementing web push notifications in my React app using Firebase. I've managed to display the notifications, but now I'm facing two challenges: 1. making the notification persist until interacted with (requireInteracti ...

Is there a way to modify the route or file name of the index.html file in a React project?

Every time I use npm build to create a React app (using the typical react-scripts/create-creact-app, etc.), the entry file always ends up in build/index.html. I attempted to move the src folder into a subfolder, but unfortunately, index.js must remain in ...

Sharing libraries among different web components can be achieved by following these steps

Embarking on a micro frontends project using custom elements has sparked the need to find a way to share dependencies across all parts of the application. I am particularly interested in integrating the Material-ui library into this structure. One idea is ...