Home > other >  How to always execute app.js code before any routes
How to always execute app.js code before any routes

Time:01-02

I am working on a simple application with routes. I have defined 2 routes as below:

App.js

import React from 'react';
import { Route, Routes, BrowserRouter } from 'react-router-dom';
import './App.css';

import Route1 from './components/Route1';
import Route2 from './components/Route2';

class App extends React.Component {

   constructor(props) {
     super(props);
   }

  componentDidMount() {
    console.log('This is from App.js')
  }

  render() {
    <BrowserRouter>
      <Routes>
        <Route path="/route1" element={[<Route1]}/>
        <Route path="/route2" element={[<Route2]}/>
      </Routes>
    </BrowserRouter>
  }
}
export default App;

Route 1

import React, { Component, createRef } from 'react'

class Route1 extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    Console.log("This is from Route1")
    // some code
  }

  render() {
    return()
  }
export default Route1

Route 2

import React, { Component, createRef } from 'react'

class Route2 extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    Console.log("This is from Route2")
    // some code
  }

  render() {
    return()
  }
export default Route1

I want to execute code written in app.js first, even before routes.

When I am on localhost:3000/route1, I can console output as below:

This is from Route1
This is from App.js

But I want to execute the app.js code before any routes, so expected putout is:

This is from App.js
This is from Route1

CodePudding user response:

Writing your code in constructor will do your job. It should look like this :

constructor(props) {
    super(props);
    console.log('This is from App.js')
  }

CodePudding user response:

The App component needs to completely mount/render its sub-ReactTree prior to itself being considered mounted/rendered. If there is some logic you want to run prior to children being rendered then you might need to add some "initial render" state to the parent and conditionally render the children once the parent component has mounted and completed the logic.

Example:

class App extends React.Component {
  state = {
    loaded: false,
  }

  componentDidMount() {
    console.log('This is from App.js');
    this.setState({ loaded: true });
  }

  render() {
    const { loaded } = this.state;
    return (
      <BrowserRouter>
        {loaded && (
          <Routes>
            <Route path="/route1" element={<Route1 />} />
            <Route path="/route2" element={<Route2 />} />
          </Routes>
        )}
      </BrowserRouter>
    );
  }
}
  • Related