Home > front end >  React-router-dom not compiling components
React-router-dom not compiling components

Time:12-05

I have problem with router-dom. I am working according to youtube tutorial, I cannot resolve below error: [landingPageLayout] is not a component. All component children of must be a or <React.Fragment>. I would be greateful for some guidance.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>  
  </React.StrictMode>,
  document.getElementById('root')
);

App.js

import './App.css';
import { Routes, Route } from 'react-router-dom';
import landingPageLayout from './components/layouts/landingPageLayout';
import homePage from './components/pages/homePage';

const App = () => {
  return (
        <Routes>
          <landingPageLayout>
            <Route path="/"> 
              <homePage/>
            </Route>
          </landingPageLayout>
        </Routes>      
  );
}

landingPageLayout.js

import React from 'react';
import Header from '../navigation/header';

const landingPageLayout = ({...otherProps}) => {
    return (
        <div>
            <Header/>
        </div>
    )
}

export default landingPageLayout;

CodePudding user response:

As Nicholas said in comments, your react components should always be capitalized.

Other than that, Routes component only accepts or <React.Fragment> as children so you can't add your layout like that. What you can do is something like this:

   const App = () => {
      return (
         <Routes>
            <Route
               path='/*'
               element={
                  <LandingPageLayout>
                     <HomePage />
                  </LandingPageLayout>
               }
            />
         </Routes>      
      );
    }

If you have several routes that need this layout, you should replace HomePage with another component that has all the routes. For example we can call it PrivateRoutes. Then in code above you replace <HomePage /> with <PrivateRoutes /> and then your PrivateRoutes component should look like this:

   const PrivateRoutes = () => {
      return (
         <Routes>
            <Route path="home" element={<HomePage />} />
            <Route path="page1" element={<Page1 /> />
            //rest of routes
         </Routes>
      );
   }
  • Related