What is the best way to switch between components when clicking on them? (The component displayed should update to the most recently clicked one

I am facing a challenge in rendering different components based on the navbar text that is clicked. Each onclick event should trigger the display of a specific component, replacing the current one. I have 5 elements with onclick events and would like to render 5 distinct components upon demand. Any assistance would be greatly appreciated!

import Sidenav from "./components/ButtonAppBar";
import AboutTab from "./components/About";
import QuoteTab from "./components/Quote";
import ProductTab from "./components/Quote";
import CalendarTab from "./components/Quote";
import ContactTab from "./components/Quote";
import "./App.css";


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      component: "About"
    };
  }

  var component = this.state.component;

switch(component) {
  case "Contact":
    return <ContactTab />;
    break;
  case "Quote":
    return <QuoteTab />;
    break;
  default:
    return <AboutTab />;
}

  render() {
    return (
      <div>
        <Sidenav>
          <h1 className="navlink" onClick={this.getComponent}>
            About
          </h1>
          <h1 className="navlink" onClick={this.getComponent}>
            Quote
          </h1>
          <h1 className="navlink" onClick={this.getComponent}>
            Schedule
          </h1>
          <h1 className="navlink" onClick={this.getComponent}>
            Products
          </h1>
        </Sidenav>
        <AboutTab />
        <QuoteTab />
      </div>
    );
  }
}

export default App;

I'm currently stuck and unable to make any progress.

Answer №1

When utilizing the element content string, this is how you can optimize your view:

import Sidenav from "./components/ButtonAppBar";
import AboutTab from "./components/About";
import QuoteTab from "./components/Quote";
import ProductTab from "./components/Quote";
import CalendarTab from "./components/Quote";
import ContactTab from "./components/Quote";
import "./App.css";


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      component: "About"
        };
        this.getComponent = this.getComponent.bind(this);
    }

    getComponent(event) {
        this.setState({ component: event.target.textContent })
    }

  render() {
    const component = this.state.component;
    let renderComponent = null; 

    switch(component) {
        case "Contact":
            renderComponent = <ContactTab />;
            break;
        case "Quote":
            renderComponent = <QuoteTab />;
            break;
        default:
            renderComponent = <AboutTab />;
    }

    return (
      <div>
        <Sidenav>
          <h1 className="navlink" onClick={this.getComponent}>
            About
          </h1>
          <h1 className="navlink" onClick={this.getComponent}>
            Quote
          </h1>
          <h1 className="navlink" onClick={this.getComponent}>
            Schedule
          </h1>
          <h1 className="navlink" onClick={this.getComponent}>
            Products
          </h1>
        </Sidenav>

        {renderComponent} 

      </div>
    );
  }
}

export default App;

If your navigation contains elements other than text, the above method may not work. In that case, consider passing a parameter with the component name to the onClick function:

<h1 className="navlink" onClick={() => this.getComponent('About')}>
    <i className='fa fa-info' /> About
</h1>

In the getComponent function:

getComponent(componentName) {
    this.setState({ component: componentName })
}

Furthermore, using a more descriptive function name like setViewComponentName can enhance clarity in understanding its purpose (setting the component name in the state):

setViewComponentName(componentName) {
    this.setState({ component: componentName })
}

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

Incorrect format for a date in AngularJS

I have a time input field where I am receiving the date and time format 'Thu Jan 01 1970 12:59:00 GMT+0530 (India Standard Time)', but I only want to display the time. Is there an issue with the time picker in AngularJS? Can anyone help me resolv ...

Angular2 can enhance your webpage with a <div> element that covers the entire screen

While working on my Angular2 application, I encountered a challenging issue that I can't seem to resolve or find a solution for. Take a look at this image of my page: https://i.stack.imgur.com/b6KlV.png Code: content.component.html <app-header& ...

Is there a way to run /_next/static/xxx.js using a script tag?

I have customized my next.config file (webpack) to generate a static JavaScript file (.next/static/loader.js). The original loader.js is an Immediately Invoked Function Expression (IIFE): (function stickerLoader(){ alert('Hello'); // ... so ...

Can someone clarify the meaning of (e) in Javascript/jQuery code?

Recently, I've been delving into the world of JavaScript and jQuery to master the art of creating functions. I've noticed that many functions include an (e) in brackets. Allow me to demonstrate with an example: $(this).click(function(e) { // ...

Get connected to your favorite music on iTunes without the hassle of opening a new window by simply clicking on the

Is there a way to call a link to iTunes (itms://...) without opening a new window? I've tried using window.open but that just opens a new window. Also, $.get('itms://...'); doesn't seem to work for me. Are there any other options avail ...

Encountering an npm issue following the execution of "npm run build": npm ERROR! code ELIFECYCLE npm ERROR! exit code 2

I'm struggling to troubleshoot an npm error I encountered after running my npm build script. The error output in the terminal looks like this: npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! [email protected] build: `webpack --mode production` np ...

Utilizing ReactJS and Gatsby Js: How to pass the value of a child component to the parent component to create a button

In my current project, I am facing an issue with a simple component that is supposed to pass back the link value from the child component to a function in the parent component. However, it seems to only call back the full function instead of its actual v ...

Can I construct an html table-esque layout employing fabric js?

https://i.stack.imgur.com/Zwkj3.jpg I'm in the process of developing a schema builder inspired by vertabelo. To achieve this, I've opted to utilize fabric.js for its interactive features. My main challenge lies in creating an HTML table-like str ...

How can I fetch the option id instead of the displayed string in the Autocomplete component?

I am currently working on a project that involves React, material-ui, and redux-form. One challenge I have encountered is with select fields that sometimes contain many options, leading users to request a select field with search functionality. To address ...

Is it possible to utilize a slot within a Vue.js loop?

I am encountering an issue with a template that is utilizing v-for to loop through. The template includes a named slot where the name is dynamically assigned within the loop. However, no content is displaying as expected. Can someone help me identify wha ...

What is the best way to incorporate Form Projection into Angular?

I have been attempting to incorporate form projection in Angular, inspired by Kara Erickson's presentation at Angular Connect in 2017, but I am encountering difficulties and errors along the way. view talk here The code provided in the slides is inco ...

Is there a way to define the route path when using MemoryRouter in Jest without using location or history objects?

Apologies if this question has already been asked before. I have a query regarding MemoryRouter in React. I am able to set initialEntries and initialIndex to customize "location" and "history", but the "match" parameter does not update as expected. It is ...

How can I emphasize the React Material UI TextField "Cell" within a React Material UI Table?

Currently, I am working on a project using React Material UI along with TypeScript. In one part of the application, there is a Material UI Table that includes a column of Material TextFields in each row. The goal is to highlight the entire table cell when ...

The [image link] in the NextJS image was loaded in advance using link preload, but it was not utilized within a short time after the window finished loading

While working on my blog website with NextJS, I encountered a warning in the console related to using next/image: The resource http://localhost:3000/_next/image... was preloaded using link preload but not used within a few seconds from the window's lo ...

Issue with jQuery AJAX request not working as expected

I'm currently utilizing Rapid API to store my users' emails and passwords. Upon clicking, my send function should trigger, however, it seems that the program is not progressing through the AJAX call. I'm at a loss on how to proceed. Any ass ...

How can I incorporate a standalone Vuetify component into my Nuxt.js project?

Using Vuetify with nuxt.js specifically for the dashboard layout - how can I achieve this in my nuxt.config.js file? modules: [ //['nuxt-leaflet', { /* module options */}], 'bootstrap-vue/nuxt', '@nuxtjs/ax ...

Achieving cross-browser compatibility with JSONP and supporting IE9 syntax in jQuery, as well as ensuring functionality

I am encountering an issue with a specific part of my code that needs to be utilized when an IE browser is detected, but removed when any other browser is in use: $.ajax({ url: 'http://mapit.mysociety.org/areas/'+ulo, ...

Dynamically created span element in script facing issues in MVC application

I have a single MVC project where, in the BusinessPosition.cshtml file, I am dynamically creating a tree view at runtime. By default, it displays the main child of the root node upon page load, like this: <ul class="col-lg-20 col-sm-12 col-xs-12" style ...

Unable to locate the module model in sequelize

Having some trouble setting up a basic connection between Postgres and SQL using Sequelize. I keep getting an error where I can't require the model folder, even though in this tutorial he manages to require the model folder and add it to the sync, lik ...

Creating an Application with Multiple Pages Using React and Material-UI

In my development project, I am utilizing Meteor, React, and Material-UI to build an application. Simplifying the scenario, the app is divided into two main sections: home and user. Both home and user pages are required to have a consistent layout featuri ...