Designing an interactive header interface using React and Material UI

My header.jsx file contains the following code:

// Default Import Statements 
var Login = require(login.jsx)
const HeaderComponent = React.createClass({

  getInitialState () {
    return {
      loggedIn: false,
    };
  },
  render() {
    return (
      <Toolbar>
        <ToolbarGroup key={1} float="right">
          <Login />
        </ToolbarGroup>
      </Toolbar>
    );
  }
});

module.exports = HeaderComponent;

The Login Component (login.jsx) looks like this:

// Default Import Statements

var LoginDialog = React.createClass({

  render() {
    return (
      <div>
        <Dialog
          title="Login"
          ref="loginDialog"
          autoScrollBodyContent = {true}
          onRequestClose={this._cancelTouchTap}
          open={this.state.open}>
          <form action="/login" method="post" autoComplete="off">
            <div>
              <TextField hintText="Email Field" ref = "email" />
            </div>
            <div>
              <TextField hintText="Password" type="password" ref = "password"/>
            </div>
            <div>
              <RaisedButton label="Submit" onTouchTap={this._submitTouchTap}/>
              <RaisedButton label="Cancel" onTouchTap={this._cancelTouchTap}/>
            </div>
          </form>
        </Dialog>

        <FlatButton label="Login" style={loginSpacing} primary={true} onTouchTap={this._handleTouchTap} />

      </div>
    );
  },

  _submitTouchTap: function(){
    var primaryEmail = this.refs.email.getValue();
    var password = this.refs.password.getValue();
    var data = {
      primaryEmail: primaryEmail,
      password: password
    };
    $.ajax({
      url: '/login',
      dataType: 'json',
      type: 'post',
      data: data,
      success: function(data) {
        console.log(data);
      }.bind(this),
      error: function(xhr, status, err) {
        this.transitionTo('/login'); 
      }.bind(this)
    });
    this.refs.loginDialog.setState({open: false});
  },

  _cancelTouchTap: function(){
    this.refs.loginDialog.setState({open: false});
  },

  _handleTouchTap() {
    this.refs.loginDialog.setState({open: true});
  }
});
module.exports = LoginDialog;

I am looking to update the header's loggedIn state to true once the ajax call returns success when a user logs in. How can I pass data from the child login.jsx file to the parent header.jsx file to achieve a Dynamic UI for the header?

Once a user is logged in, the state of loggedIn in the header component should change to true, triggering the display of a different header than the current one.

Answer №1

To implement a callback function, you can follow this example:

var Login = require(login.jsx)
const HeaderComponent = React.createClass({

  getInitialState () {
    return {
      isLoggedIn: false,
    };
  },
  render() {
    return (
      <Toolbar>
        <ToolbarGroup key={1} float="right">
          <Login onLoggedIn={this._handleLogIn}/>
        </ToolbarGroup>
      </Toolbar>
    );
  },
  _handleLogIn: function (data) {
    console.log(data);
    this.setState({isLoggedIn: true});
  }
});

module.exports = HeaderComponent;

var LoginDialog = React.createClass({

  render() {
    return (
      <div>
        <Dialog
          title="Login"
          ref="loginDialog"
          autoScrollBodyContent = {true}
          onRequestClose={this._cancelTouchTap}
          open={this.state.open}>
          <form action="/login" method="post" autoComplete="off">
            <div>
              <TextField hintText="Email Field" ref = "email" />
            </div>
            <div>
              <TextField hintText="Password" type="password" ref = "password"/>
            </div>
            <div>
              <RaisedButton label="Submit" onTouchTap={this._submitTouchTap}/>
              <RaisedButton label="Cancel" onTouchTap={this._cancelTouchTap}/>
            </div>
          </form>
        </Dialog>

        <FlatButton label="Login" style={loginSpacing} primary={true} onTouchTap={this._handleTouchTap} />

      </div>
    );
  },

  _submitTouchTap: function(){
    var email = this.refs.email.getValue();
    var password = this.refs.password.getValue();
    var data = {
      email: email,
      password: password
    };
    $.ajax({
      url: '/login',
      dataType: 'json',
      type: 'post',
      data: data,
      success: function(data) {
        console.log(data);
        this.props.onLoggedIn(data);
      }.bind(this),
      error: function(xhr, status, err) {
        this.transitionTo('/login'); 
      }.bind(this)
    });
    this.refs.loginDialog.setState({open: false});
  },

  _cancelTouchTap: function(){
    this.refs.loginDialog.setState({open: false});
  },

  _handleTouchTap() {
    this.refs.loginDialog.setState({open: true});
  }
});
module.exports = LoginDialog;

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

Submit a form using Ajax without having to reload the page

Seeking help for implementing an ajax form submission with four answer options to a question. The goal is to submit the form without reloading the page upon selecting an option. Below is the code I have been working on. Any suggestions or solutions are wel ...

Using TypeScript to call Node.js functions instead of the standard way

Can someone assist me with the issue I'm facing? I have developed a default node.js app with express using Visual Studio nodejs tools, and now I am attempting to call the setTimeout function that is declared in node.d.ts. The code snippet in question ...

In Angular, the ng-click directive that assigns the value of tab to $index does not seem to be functioning properly

I encountered an issue within my app <li ng-repeat="name in tabs track by $index" ng-class="{selected: tab==$index}" ng-click="tab = $index">{{name}}</li> After clicking on each item, the selected class remains enabled and switching to anothe ...

The scatterplot dots in d3 do not appear to be displaying

My experience with d3 is limited, and I mostly work with Javascript and jQuery sporadically. I am attempting to build a basic scatterplot with a slider in d3 using jQuery. The goal of the slider is to choose the dataset for plotting. I have a JSON object ...

Merge information from various sources using ajax

Currently, I have a single ajax request that retrieves data from an API and uses it to generate a table. Now, I'm looking to modify the code so that it can retrieve data from two different URLs and merge them into the same table (retTable). Below is ...

I could use a hand here - I'm getting an error message that says "Module not found: 'react-dev-utils/WatchMissingNodeModulesPlugin'

Error: The 'react-dev-utils/WatchMissingNodeModulesPlugin' module cannot be found Require stack: - C:\Users\stromboli\IdeaProjects\projects-ui\config\webpack.config.js - C:\Users\stromboli\IdeaProjects ...

I'm encountering an error when trying to pass multiple parameters in an AJAX request

I am trying to pass three parameters to my ajax code. Here is the snippet of my code: $(document).ready(function () { SearchText(); }); function SearchText() { $("#txt712").autocomplete({ source: function (request, resp ...

React Material-UI components (Slider/Select) "onChange" event does not update the value instantly, it shows the result of the previous click

My goal is to utilize Slider/Select for capturing user query parameters, which will then trigger changes in the URL (via handleChange) and subsequently make API calls using fetch hooks. However, I've encountered an issue where adjusting the Slider va ...

Angular rxjs: Wait for another Observable to emit before subscribing

My setup involves having 2 subscriptions - one is related to my ActivatedRoute, and the other is from ngrx Store. ngOnInit() { this.menuItems$ = this.store.select('menuItems'); this.menuItems$.subscribe(data => { this.menuItem ...

When processing a response from the backend (using express js), cookies are not being received in the browser while on localhost

I'm currently facing some difficulties with implementing authorization cookies within my application. Whenever I attempt to send a GET request to my API (which is hosted on port 8080) from my React frontend (running on port 3000), the cookies that I ...

Working with Scala PlayFramework and Angular JS can be overwhelming due to the amount of duplication and confusion that arises from mixing different concepts

Attempting to build an application using the combination of playframework, scala, and Angular JS, I aimed to create a web app that functioned seamlessly whether JavaScript was enabled or disabled in the browser. This requirement is common when developing a ...

Learn the process of updating Datatables' multiple column headers in real-time using ajax and jquery, all without the need to refresh

My goal is to dynamically change the column number and header of a table based on the return value of an AJAX call in conjunction with DataTables jQuery plugin. Below is the JavaScript and jQuery code I am currently using: $( document ).ready(function() { ...

The print preview displays a single div in an incorrect location

I have successfully created a javascript plot and wanted to incorporate a legend that overlaps the plot. Unfortunately, the function I used does not support directly overlapping legends, but it does allow for placing the legend in a separate div. To work a ...

Switching the default browser for npm live-server

When I use the npm live-server package to preview my website as it changes, it keeps opening in Edge even though Chrome is set as my default browser on my system. I attempted to use the command suggested on the npm website: live-server --browser=chrome H ...

Ways to restrict input text to a specific set of values

When using an input text form, I need to ensure that users only insert values ranging from 1 to 10. However, my attempts to utilize a mask for customization have resulted in allowing values higher than 10. How can I restrict the input to only be allowed b ...

How to pass an item as a parameter to a computed property in Vue.js, and have it return a sorted child array within a

After spending some time searching on Google, I am still struggling to find a solution for this issue. I have a list of "Intents" that contain nested lists of "Entities" created using v-for loops. The Intents are already computed, but now I need to dynam ...

Trouble with Google Bar Chart's Background Color not Updating

I'm having issues with the background color in my google Material Charts static api library. Despite entering a specific color code, the change is not being reflected when the page loads. These are the options I have set: var options = { b ...

Utilize State Hooks with arrays and objects

***I'm looking to define the initial state as an array with two objects, each containing another array. However, I'm having trouble setting this state using setState. The state I am trying to set should consist of two objects, each with two prop ...

Testing functions with Jest mocks

In my unit test, I have encountered an issue with Jest mocking behavior. Here is a simplified version of the code: import ApiWrapper from '../../services/api_wrapper'; jest.unmock('../helper') describe('Helper', () => { ...

What are the steps to integrate material-ui with styled-components effectively?

import styled from "styled-components"; import Button from "@material-ui/core/Button"; export const StyledButton = styled(Button)` margin: 20px; `; I'm having trouble adjusting the button styling. How can I add a margin to the ...