Creating a Welcome Page for my React Application with IndexRoute

I am in the process of setting up a landing page that will then redirect to my main home page using React. I have created a component for the landing page named Splash. I am attempting to utilize IndexRoute to make sure my app initially displays Splash as the first page. Below is my code snippet from app.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import {Provider} from 'react-redux';
import store from '../store';

import App from 'views/App';
import Home from 'views/Home';
import About from 'views/About';
import Cart from 'views/webcart';

ReactDOM.render(
    <Provider store={store}>
        <Router history={hashHistory}>
            <Route path='/' component={App}>
                <IndexRoute component={Splash} />
                <Route path='about' component={About} />
                <Route path='Cart' component={Cart} />
                <Route path='Home' component={Home}
            </Route>
        </Router>
    </Provider>,    
    document.getElementById('app') // eslint-disable-line
);

The content of my splash.js file is as follows:

import React, { Component } from 'react';
import Woods from './woods.jpeg';
import Logo1 from './whitestar.png';


export default class Splash extends Component {
    render() {
        return(
            <div id='Splashwrapper'>
                <img src={Woods}></img>
                <img src={Logo1}></img>
            </div>    
        );  
    }
}

An issue I am facing is that both my home and landing pages are displaying together instead of just the landing page showing up initially. How can I resolve this?

EDIT

In my Home component, there might be an opportunity to accomplish what I intend with the landing page:

import React, { Component } from 'react';
import { Link } from 'react-router';

import Jag from './jag.jpg';
import Jag2 from './jag2.jpg';
import Logo from './nsplogo.jpeg';

var Music = React.createClass({
        render: function() {
            return (
                <div>
                    <h2> BBB </h2>
                </div>
            );

        }
    });

export default class Home extends Component {
    soundCloud() {
        var SC = require('soundcloud');

        SC.initialize({
            client_id: 'YOUR_CLIENT_ID',
            redirect_uri: 'http://example.com/callback'
        });
    }

    constructor(){
        super();
        this.state = {
            showSquareOne:false,
            showSquareTwo:false,
        }
        this.toggleShowSquare = this.toggleShowSquare.bind(this);
    }

    toggleShowSquare(property){
        this.setState((prevState)=>({[property]:!prevState[property]}))
    }

    componentDidMount () {
        window.scrollTo(0, 0)
    }



    render() {
        return (
            <div className='Home' id='Home'>  
                <div id="musicwrapper" className={this.state.showSquareThree?'':'invisible'}>
                    <div id='musicsquare' className={this.state.showSquareOne?'':'invisible'}>
                        <h1>AAA</h1>
                        <div id="musicpics">
                            <img src={Jag} tabIndex="1" id='jag1'></img>
                            <img src={Jag2} tabIndex="1" id='jag2'></img>
                        </div>
                        <iframe width="560" height="315" src="" frameBorder="0" allowFullScreen></iframe>
                        <div id='Body'></div>
                    </div>
                </div>
                <div id='musicMenu'>
                    <ul>
                        <li id="music" onClick={()=>this.toggleShowSquare('showSquareOne')}>Music</li>
                        <li id="shows" >Shows</li>
                        <li id="collections">Collections</li>
                    </ul>
                </div>
            </div>
        );
    }
}

Additionally, I have a Menu component in my app that always stays on top of the page, causing issues with the landing page display. Even though the landing page is present, the menu still shows up simultaneously.

Answer №1

Introduction: Here is a straightforward approach to displaying a splash screen. I will outline the necessary modifications to the component lifecycle to achieve this functionality.

If you integrate this into your Main component, the splash screen will appear every time Main mounts. To display it only once, consider placing it in your top-level Root component since it loads with the page.

To begin, add a key in your state constructor to track the visibility of the splash:

this.state = {
  splash: true
};

In the componentDidMount method, set up a Timeout that triggers this.setState after a specified duration (Use Fat Arrow Syntax for maintaining the this reference):

componentDidMount() {
  setTimeout(() => {
    this.setState({splash: false});
  }, 1000); // 1000ms = 1 second
}

Lastly, in the render function, evaluate the splash boolean and return the splash div if it's true:

render() {
  if (this.state.splash) {
    return <div className="splash">Splash</div>
  }
  return (...Default Content...)
}

If utilizing Redux, consider storing the splash toggle in the store and passing it down to your application.

To incorporate animations for a seamless transition, render the splash screen initially and use the boolean to toggle a class that fades it out and adjusts the z-index OR explore options like React Transition Group.

I hope this information proves helpful.

Answer №2

To make this work, you must specify the Splash route separately.

ReactDOM.render(
    <Provider store={store}>
        <Router history={ hashHistory }>
            <Route path='/' component={ App }>
                <IndexRoute component={ Splash } />
                <Route component={Splash} /> // Don't forget to include this line.
                <Route path='about' component={ About } />
                <Route path='Cart' component={ Cart } />
                <Route path='Home' component= { Home }
            </Route>
        </Router>
    </Provider>,    
    document.getElementById('app')
);

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

I kindly request your assistance in resolving the issues with the append() and empty

Here is some code I've been working on: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ ...

Creating a CSS grid layout with a scrollbar positioned on the left side and content filling from left to right

How can I move the scrollbar to the left while keeping ng-repeat population from left to right? I'm using an ng-repeat to fill a grid that is 3 by X (Width by height). By default, the scroll bar appears on the right side. I want to position it on the ...

When a function is passed down to a child component in React Functional Component, the context can be lost

Within my parent component DrawingGrid, I have a child component called ContextMenu. Inside the parent component, there is a variable named existingPoints that should delete a point when the "Delete" button in the ContextMenu related to that point is click ...

What is the best way to include a button that will appear next to the text for every item in React Native?

I'm facing a challenge in adding a button next to each list item and I could use some guidance on how to achieve it. return ( <View> <Text style={styles.Blue}>My List</Text> <FlatList data={this.state.ListData} ...

The JavaScript array created from parsing JSON returns a value of undefined

Once again, the gecko scenario! The JSON used in this script to fill a listbox has been validated by JSONLint. The code snippet below demonstrates how the parsed data is placed in arrays: pdata = jQuery.parseJSON(data); ctype = pdata[0]; stype = pdata[1]; ...

Is there a way to ensure that a React or Node application is fully compliant with OWASP security guidelines?

Although I have a general understanding of OWASP, I am struggling to figure out how to effectively assess the security of an application built with React and Node. I have familiarized myself with the top 10 security risks, but I am looking for a more con ...

Unable to select checkbox within a table using Selenium WebDriver with Java

Having trouble checking a checkbox inside a table using Selenium Webdriver in Java? Even with version 2.52.0 of Selenium, the element not found error persists across different web browsers. The iFrame seems to be correct as I can interact with other compon ...

The lack of synchronization between the updated state in one function and its counterpart is causing discrepancies, resulting in the incorrect information being sent to the API

Whenever I press the following button: <Button onClick={(e) => { addToCard(item); handleprisma(); }} > add to cart </Button> This function is meant to add the item to my shopping cart: const addToCard = (item) => { co ...

Sails.js Unidirectional Association

I'm currently working on establishing a relationship between two MySQL tables in sails js. I went through the documentation regarding this topic which can be found here. However, I encountered an error message: error: Sending 500 ("Server Error") re ...

Issue with loading 3D model using three.js in a web browser

While using ASP.Net core, I encountered an issue with loading a 3D model using the Three.js library. The error message "ERR_NAME_NOT_RESOLVED" appears when trying to load the scene. You can view the code in my VS View here. This code works perfectly in VS ...

The XMLHttpRequest function successfully logs data in the console, but does not return the data within the function itself

I find it puzzling that the console.log statement at the end of the code snippet displays the data as expected, while the return optiondata line does not. function populate_selectbox() { var ajaxRequest; try { // Opera 8.0+, Firefox, S ...

Showing the URL beyond the search bar: A Guide using PHP, JavaScript, and HTML

How can I display the URL link outside the search box instead of opening a new page with the search result? I want to show the full URL (https://www.php.net.) below the search box, not within the search results. I only want to see the URL, not the contents ...

Auth0 encountering issues retrieving ID token and user metadata

Currently in the process of integrating Auth0 into a Vue.js/Node.js application, I have successfully enabled user registration and login functionality (to /callback). Although the manual addition of data to the user metadata section is functional at this s ...

Responsive columns with maximum width in Bootstrap

Currently, I'm working on coding a portion of a single-page responsive Bootstrap layout that features two columns of text placed side by side. The request from the designer is for these columns to have a maximum width, but to be centered until they hi ...

Comparison of the "Proposed Recommendation" versus the "Candidate Recommendation"

In a recent piece about HTML5, it was mentioned that the Proposed Recommendation date is set for 2022, while the Candidate Recommendation date is from 2012. I'm curious to understand the distinction between the "Proposed Recommendation" and the "Cand ...

How can I bind Angular to the selection of a file input field?

I am facing an issue with my upload form where the displayed filename is showing a virtual filepath instead of just the filename itself. How can I improve the binding to only display the filename (like selected.files[0].name) without any virtual path? My ...

Creating an NPM Module: Importing your own package as a dependency

Currently, I am in the process of developing a new NPM package. The repository includes an examples directory containing some JavaScript code that is compiled and served locally (or potentially through github.io). The configuration is reminiscent of the s ...

Guide to displaying Fontawsome icons with CSS2D Renderer/Object

I am trying to display the map-marker-exclamation icon from the FontAwsome library on top of a three.js cube, but unfortunately, the icon is not rendering properly. Can someone guide me on how to successfully render a FontAwsome Icon using three.js? Thank ...

Vue.js is having trouble locating images

I am currently using Vue-CLI with the latest version of Vue (3.9.3), but I am facing an issue where Vue cannot locate my images. Below are some screenshots for reference. Why are the images not showing up? First image (Structure) Second image (template) ...

Using conditional statements in CodeIgniter to display various menus

I encountered an issue with a variable in my code. When I attempt to retrieve its value, it shows up as undefined despite having stored the session of the variable "$level" and passing it to the view. I find it strange that the condition of the variable tu ...