What is the best way to display a react component only when the route changes?

As a beginner in the world of React, I am currently working on creating a simple React application. My goal is to display a component based on the current route.

index.js

var React = require('react');
var ReactDOM = require('react-dom');
var createReactClass = require("create-react-class");
import { Router, Route, browserHistory, Link } from "react-router";

var About = require("./about");
var Admin = require("./admin");

var App = createReactClass({
    render: function() {
        return(
            <Router history={browserHistory}>
        <Route path={"/"} component={RootComponent}></Route>
        <Route path={"/about"} component={About}></Route>
                <Route path={"/admin"} component={Admin}></Route>
            </Router>
        );
    }
});

// Create a component
var RootComponent = createReactClass({
  render: function() {
        var currentLocation = this.props.location.pathname;
    return(
      <div>
        <Link to={"/about"}>About</Link>
                <Link to={"/admin"}>Admin</Link>
        <h2>This is the root component</h2>
      </div>
    );
    }
});

// Put component into html page
ReactDOM.render(<App />, document.getElementById("app_root"));

Is there a way to use an if else condition to determine what content to render on a layout based on the code below?

var RootComponent = createReactClass({
  render: function() {
        var currentLocation = this.props.location.pathname;
        if (currentLocation == "admin") {

   return(
      <div class="admin_template">
      </div>
    );

        } else {

   return(
      <div class="home_template">
      </div>
    );

        }
    }
});

I am looking for a way to detect when a route changes after clicking a link and then display the appropriate template.

Your assistance on this matter would be greatly appreciated. Thank you!

Answer №1

To render specific components based on the route, you can incorporate an additional

<Router><Route /></Router>
switch within your RootComponent, much like how it was implemented in the App component.

Answer №2

If you're working in index.js, all you need to do is add another route. It sounds like you want to differentiate between an admin page and a user page, which can be achieved by using an if-else condition to render content. However, this isn't the best approach because we have react-dom available but are not utilizing it.

Here's one of many solutions that might work for you:

import { Route, Switch } from 'react-router-dom';
const wrappedRoutes = () => (
  <div>
      <Route path="/" component={abc} />
      <Route path="/bcd" component={bcd} />
    </div>
  </div>
);

const Router = () => (
      <Switch>
        <Route path="/admin" component={wrappedRoutes} />
      </Switch>
);

Now, when you navigate to the URL /admin, you'll see the component abc. If you go to /admin/bcd, you'll see the component bcd.

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

Launching another browser tab quietly

My goal is to open a new tab in the background, similar to how it works on vouchercodes where you click a link and return to the previous tab. I have read that this may not be possible with Javascript, but I am using JQuery mobile. Here's what I&apos ...

Switching from a vertical to horizontal tab layout in Angular 4 Material 2 using MD-Gridlist

I'm currently trying to modify the tabbing functionality within an MD-Gridlist so that it tabs horizontally instead of vertically. I've experimented with tab indexes but haven't had any success. My goal is to enable horizontal tabbing throug ...

Ways to refresh my $scope once new data is inserted into the SQL database

As I implement the angularjs/SQL technique to fetch data from a database, the code snippet below demonstrates how it is done: $http.get("retrieveData.php").then(function(response){ $scope.tasks = response.data.tasks; }) In addition, there is a functi ...

Is PM2 Functioning Properly Despite Experiencing High Restart Frequency and Zero Errors?

Lately, I have been using PM2 and it seems to be working perfectly in terms of functionality. However, I have observed that when I leave my node app running overnight and check it in the morning, the "restart" count has increased by around 20 times. For ...

AJAX is designed to only modify one specific Django model instance at a time

My Django project displays a list of "issue" objects, each with a boolean field called "fixed". I am looking to implement a feature where users can press a button that will modify the "fixed" status using Ajax. However, currently, the button only changes o ...

Determine the active animation on an element using jQuery or JavaScript

Can you provide the code for the know_anim() function that can determine which animation is currently running on the '#div' element? Check out the jsFiddle link for reference:https://jsfiddle.net/himavicii/bL0nsjeL/ function moveLeft() ...

How can I fix the issue with Parallax scrolling not functioning properly? (Using Next.js Image + Tailwind)

What am I missing to get parallax scrolling to work? <div className="h-screen"> <div className="relative h-full w-full bg-cover bg-fixed bg-center bg-no-repeat"> <Image src="https://images.unsplash.com/photo-1454496522488-7a8e488e86 ...

I'm looking for assistance on how to set the minimum height using jQuery. Can anyone provide

My attempt to use the minHeight property in one of my divs is not successful, and I am unsure why... <div id="countries"> <div class="fixed"> <div class="country" style="marging-left:0px;"></div> <div class="country"&g ...

How to ensure Angular mat-button-toggle elements are perfectly aligned within their respective groups

https://i.stack.imgur.com/Wjtn5.png Hello there, I'm trying to make the numbers in the first group match the style of the second group (noche, mañana...). I've set both the group and individual element width to 100%, but the numbers beyond 22 ...

Is it possible to access all the variables within a specific scope or explore different scopes using console.log?

In the process of writing a graph algorithm, I am currently working on implementing a removeEdge method in the graph prototype. This method takes two arguments, which are the two nodes that will be losing their connection. I have successfully achieved a ...

I encounter issues when entering conditions in my JavaScript code

Being new to JavaScript, I'm trying to save the Vector position and use two buttons (forward and backward) to move the Camera to that specific location. I also attempted to incorporate 'gsap' for smooth movements, but unfortunately, the code ...

Pass data from a JavaScript array to PHP with AJAX

I have sought assistance both here and on stackoverflow in creating an invitation function. Within an AJAX-based search box, users can invite teams. Upon locating and selecting a team, it is stored in an array. However, I now need to access the data from t ...

How to retrieve a MySQL column in Node.js using template literals

I have been trying to retrieve a field from MySQL in my Node.js file using template literals, but I am struggling to get the value. In my post.controller.js file, you can see where it says message: Post ${body.post_id} was successfully created, with post_i ...

What is the best approach to limit the return type of a function in JSX?

Is it possible to create a function where the return type should be a specific JSX type? For instance: const setHosting : <GitlabLogo> | <GithubLogo> = (h: Hosting) => ??? In this case, the return type must either be <GitlabLogo> or ...

Implementing a default value for a date input in React.js - A step-by-step guide

I am having trouble displaying the value of "dataSubEvento" in the input field. **const [dataSubEvento, setDataSubEvento] = useState( props.activeSubEventData.data ); <input className="createsubevent-item_input" ...

bootstrap accordion animation

#accordion { .card { border: unset !important; .card-header { @extend .text-xx-large; background-color: $white; padding: ($spacer * 3.44) 0px ($spacer * 3.44) 0px; } } } .card-header { h5 { a{ color: $d ...

Locating items within a complex array and identifying their corresponding positions

I recently found an interesting code snippet from a different question that allowed me to identify an object. However, I am now faced with the challenge of determining the position of that object within the array. Let's take a look at the example belo ...

Bottom section goes haywire in Chrome when clearfix is applied to a div above

When I remove the clearfix div above the footer, the text aligns correctly on Firefox. However, this causes issues with other elements on the page. It's puzzling how the clearfix is impacting the footer in this way... Here is a link to my page: ...

Instructions for creating a string builder append button that reveals a concealed modal

I'm attempting to add a button using a string builder to append the button in a placeholder. The button will be appended based on a value in the data table. The button append operation is working correctly, but the button's functionality to revea ...

Animated banners using Jquery

I've been working on creating an animated banner for my website. I put together each image separately and envisioned using jQuery to smoothly transition between them within a table layout. It's hard to explain, so I might just sketch it out inste ...