It's important to understand how to correctly send state values from a parent component to a child component

I have a tab menu in my code and I am looking to implement a feature where tabs can be switched using a button. The challenge is passing the values of these tabs into the onclick function of the button in order to navigate between them.

Here is an example:

<Tabs value={this.state.value} onChange={this._handleChange}>
     <Tab label="1" value={1}>
         <RaisedButton label="Next" onTouchTap={this._handleChange} />
     </Tab>
     <Tab label="2" value={2}>
         <RaisedButton label="Next" onTouchTap={this._handleChange} />
     </Tab>
     <Tab label="3" value={3}>
         <RaisedButton label="Next" onTouchTap={this._handleChange} />
     </Tab>
</Tabs>

The _handleChange function updates the state with the value of the next tab

_handleChange: function(value) {
    this.setState({
      value: value,
    });
    console.log(this.state);
  }

I am trying to connect the onTouchTap event with the onChange event from the main tabs element, but I am unsure of how to achieve this. My objective is to cycle through the three available tabs: clicking "Next" on tab1 should move to tab2, then tab3, and back to tab1.

If anyone has insight on how to accomplish this task, it would be greatly appreciated. Note that I am utilizing material UI components if you find the elements unfamiliar.

Answer №1

Here is a way to accomplish it:


<Tabs value={this.state.value} onChange={this._handleChange}>
     <Tab label="1" value={1}>
         <RaisedButton label="Next" onTouchTap={this._handleChange.bind(this, 2)} />
     </Tab>
     <Tab label="2" value={2}>
         <RaisedButton label="Next" onTouchTap={this._handleChange.bind(this, 3)} />
     </Tab>
     <Tab label="3" value={3}>
         <RaisedButton label="Next" onTouchTap={this._handleChange.bind(this, 1)} />
     </Tab>
</Tabs>

Answer №2

Although the siu query was accurate, it is important to remember that setState() functions asynchronously.

Your console.log immediately following

this.setState({
  value: value,
});

may produce a different output than anticipated.

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

Having trouble with the Refresh or Direct Url not functioning properly after bundling with webpack in a React JS project

I encountered an error where the react js app with browser history was only functioning normally. However, after building with webpack, I faced issues with refreshing or pasting relative URLs. Switching to hash history resolved the problem. Despite trying ...

Tips for creating responsive content within an iframe

I have inserted a player from a website that streams a channel using an iframe. While I have managed to make the iframe responsive, the video player inside the iframe does not adapt to changes in viewport size. Despite trying various solutions found online ...

Unexpected value assigned to private variable within a PHP class

Initially, the issue I am encountering originates from my PHP class that is called by a PHP file accessed through an AJAX call. The main problem lies in the fact that the return value does not align with the sybase_result value. What could possibly be mis ...

Controlling the window opener; Inserting text into an element in the parent window

A pop-up window allows users to select files, then displays the selected image's URL. However, I need to take additional steps beyond that. I am seeking a method to input the URL into an input element on the parent window. window.opener.document.wri ...

Setting the texture for a loaded glb model using Three.js

After successfully loading a basic glb model created in SketchUp using Three.JS, I encountered an issue with displaying text on the model. The model includes a group identified as Text. Despite being able to load and visualize the model correctly in Three ...

Tips for concealing a tag for Autofill on click in Material-UI?

Hello there, I'm a newcomer to Material-ui and I've been experimenting with customizing the Autocomplete component from @material-ui/labs. I'm trying to figure out how to hide the field label. Can anyone provide guidance on how to achieve th ...

Bootstrap Collapse function might not function properly immediately following the execution of Collapse Methods

Here is the reference link: http://jsfiddle.net/72nfxgjs/ The code snippet I used is from w3schools: http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_collapse&stacked=h <script type="text/javascript"> $("#collapse1").col ...

What could be causing this slider to malfunction in Firefox?

I have recently developed a slider on this page: While the slider functions smoothly in Chrome, I am facing compatibility issues with Firefox. Can anyone shed some light on why this might be happening? Here is the HTML, CSS, and JS code used for the slid ...

Retrieve HTML classes within JavaScript textual templates

<!-- TEMPLATE UPLOAD --> <script id="template-upload" type="text/x-tmpl"> {% for (var i=0, file; file=o.files[i]; i++) { %} <tr class="template-upload fade"> <td class="name"><span>{%=file.name%}</span></td> <td ...

AngularJS directive facing a callback problem

Having trouble with callbacks while calling a service function This is the function defined in registrationService function checkUserAccess(incentiveLevel, callback, displayRegistrationView) { var url = "..."; httpWrapperService. ...

How to troubleshoot the EXPO_DEBUG problem in React Native

Whenever I try running expo start in my Mac terminal, I encounter an issue with the following message: Could not access packager status at http://localhost:19001/status. Are you sure the packager is running and reachable? Set EXPO_DEBUG=true in your e ...

Determine if a user's inputted number matches a randomly generated number using Javascript

I am trying to generate a random number, prompt the user to input a number, compare the two, and display a popup indicating whether they match or not. Below is the code that I have written for this functionality. function generateRandomNumber() { ...

How can I stop grid items from overlapping in MUI Grid?

I have a grid setup using MUI Grid with two items, each containing a textbox. On smaller screensizes, the textboxes should be stacked on top of each other like this: And on larger screensizes, they should be displayed next to each other: However, at cer ...

Angular Bootstrap Modal provides a sleek overlay for user input forms

Trying to access an angular form within scope for validation purposes. Initial Scenario Consider the following HTML: <body ng-controller='MyAwesomeController'> <form name="fooForm"> <textarea ng-model="reason" required= ...

Is there a way to deactivate or eliminate the alert component?

I'm trying to figure out how to disable the alert in my code, but I can't seem to find a boolean parameter for this in the official documentation. import React from 'react'; import Alert from '@material-ui/lab/Alert'; export ...

Exploring the distinctions between the Decorator and Mediator design patterns when implemented in JavaScript

After delving into JavaScript patterns, I noticed some interesting differences between Angular 4 and Angular 1.x. Angular 4 employs new patterns that caught my attention. What specific patterns does Angular 4 utilize? Is it possible to incorporate the De ...

Every time I try to useNavigate, I end up with a

Welcome.js import CreatePopUp from "./popup"; import createWelcomePage from "./welcomePage"; import {BrowserRouter , Route} from "react-router-dom"; import {Routes} from "react-router" f ...

Using Axios in a VUE application to handle response data

I've been working on a VUE application and I'm currently exploring how to handle post responses with Axios. Initially, I used vue-router for fetching data but decided to give Axios a try. Axios code: methods: { sendForm () { ...

Exploring the functionalities of the useState object with mapping techniques

While attempting to convert my class-based component to a functional style, I encountered the following code: const [foo, setFoo] = useState(null); const [roomList, setRoomList] = useState([]); useEffect(() => { setRoomList(props.onFetchRooms(props.to ...

Error: Could not retrieve reactjs - promise unhandled

Encountered an error while trying to fetch data in ReactJS I attempted to modify the code as follows: headers: { 'Access-Control-Allow-Origin': '*', "Content-type": "application/json; charset=UTF-8", 'mode':&apo ...