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

The fs.fsync(fd, callback) function in the node.js API allows you

Can you explain the purpose of fs.fsync(fd, callback) in the Node.js API? fs.fsync(fd, callback) This function is used for asynchronous fsync(2). The completion callback only returns an exception if there is one. fs.fsyncSync(fd) This function is for ...

Having trouble getting Firebase phone number authentication to work with Vue.js

I am currently in the process of developing a new Vue.js application using the Webpack template. Within this app, I have implemented a /sign-in route that displays a component named SignIn. To authenticate users, I am utilizing Firebase Phone Number authen ...

Cordova encountered an error: Execution of inline script was denied due to violation of Content Security Policy directive

As I delve into the world of Cordova and jquery mobile, I encountered a perplexing error that reads: Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' data: gap: 'un ...

Does the Node Schedule library create new processes by spawning or forking them?

Is the node-schedule npm module responsible for spawning/forking a new process, or do we need to handle it ourselves? var cron = require('node-schedule'); var cronExpress="0 * * * *"; cron.scheduleJob(cronExpress, () => { //logger.info(" ...

Issues within jQuery internal workings, implementing improved exception handling for fn.bind/fn.apply on draggable elements

I've been experimenting with wrapping JavaScript try/catch blocks as demonstrated on this link. It functions properly, essentially encapsulating code in a try/catch block to handle errors like so: $.handleErrors(function(e){ console.log("an erro ...

The value of type 'string' cannot be assigned to type '"menu" | "selectedMenu" | undefined' as it is not compatible with the specified types

I'm working on creating a multiple select feature using TypeScript, material-ui, and React. I am encountering an error when trying to set MenuProps.variant = 'menu'. The error message reads: "Type '{ variant: string; PaperProps: { styl ...

steps for including a JS file into Next.js pages

Is it possible to directly import the bootstrap.bundle.js file from the node_modules/bootstrap directory? import "bootstrap/dist/css/bootstrap.rtl.min.css"; function MyApp({ Component, pageProps }) { return ( <> <Script src="node_m ...

Error 414: The URL exceeds the maximum length and cannot be processed

I am currently utilizing vuejs and sending an axios request to the server in order to download a csv file. download() { var that = this //this.records = [{id: 1, name: 'Jack'}, {id: 2, name: 'Jacky'}, {id: 3, name: &apos ...

How can I incorporate a new user interface button into Here Maps?

I have set up a default interactive map using Nokia Here Maps v3. The map contains multiple markers grouped together. Now, I am looking to add a button or some other UI element to the map that, when clicked, will call a function to zoom in as tightly as p ...

Discover each *distinct arrangement* from a given array

I'm looking to generate unique combinations of element positions in a JavaScript array. Here's the array I am working with: var places = ['x', 'y', 'z']; The combinations I want are: [0,1], [0,2], [1,2]. Current ...

What can be done to ensure that two separate react-native Picker components do not interfere with each other's

Encountering an issue with two Pickers in a react-native View. Whenever I select a value in one Picker, it causes the other Picker to revert back to its initial item in the list. It seems like the onValueChange function is being triggered for both Pickers ...

Issue with React sending a Get request to a Node server using Express

Here is a snippet of code from my React app where I am trying to retrieve data from my database based on a value that is passed. Let's start by examining the section of code that may be causing an issue: Within one of my forms, there is a function th ...

What exactly is Bootstrap - a CSS framework, a JavaScript framework, or a combination

Being new to Bootstrap, I have taken the time to explore What is Bootstrap? as well as http://getbootstrap.com/. From what I understand so far, Bootstrap is a CSS framework that aids in creating responsive designs that can adapt to various devices. Essent ...

Triggering two function calls upon submission and then waiting for the useEffect hook to execute

Currently, I am facing a challenge with form validation that needs to be triggered on submit. The issue arises as some of the validation logic is located in a separate child component and is triggered through a useEffect dependency from the parent componen ...

Most efficient method for using jQuery to load content and populate form fields

My current process involves utilizing jQuery to send a post request to a page that responds with a JSON Array. Within this method, I call another function/Controller which displays an HTML form after loading it via get request. Subsequently, the form field ...

Display the results from the API in a div using Vue.js

Currently working on implementing dynamic buttons to fetch data from an API call. Struggling with pushing the data array to the template and div. Here is my VueJS setup: var example = new Vue({ el: '#example', data: function () { ...

Using JavaScript to submit a form to two separate destinations and subsequently validating it with jQuery

I am facing an issue with a form named #summaryforms which offers users the choice to either book now or book later. Below are the buttons available: <div class="bookingbuttondiv"> <input type="hidden" name="bookingid" value="<?php echo $b ...

What is the best way to retrieve the value of a dropdown menu in blueimp with PHP?

<select name="select1"> <option> Demo1 </option> </select> <select name="select2"> <option> Demo1 </option> </select> i have two select boxes, i want send the values to the uploadhandler and insert in to da ...

What methods can you use to locate the CSS selector within HTML that meets certain criteria?

Is it possible to parse a given link and find CSS selectors with attributes that partially or completely match a specific keyword? For example, if the keyword is "print," I want to identify all CSS selectors in the link containing "print" in their name, id ...

Extract content from an HTML form within a specific cell using Cheerio

A sample HTML table is displayed below: <tr class="row-class" role="row"> <td>Text1</td> <td> <form method='get' action='http://example.php'> <input type='hidden' ...