1

I'm trying to figure out how to use react-router for applications with react. But my route part doesn't work, it shows a blank page in any case.

Here are the code parts of the files used:

index.js

import ReactDOM from "react-dom"
import App from './components/App';
import 'bootstrap/dist/css/bootstrap.min.css'

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

App.js

import { Container } from "react-bootstrap";
import Signup from "./Signup";
import HomePage from "./HomePage";
import { AuthProvider } from "../context/AuthContext"
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'

function App() {
 return (
   <Container className="d-flex aling-items-center justify-content-center" style={{ minHeight: "100vh" }}>
   <div className="w-100" style={{ maxWidth: "400px", display: "flex", flexDirection: "column", justifyContent: "center"}}>
     <Router>
       <AuthProvider>
         <Routes>
           <Route path="/" element={<HomePage />}></Route>
           <Route path="/signup" element={<Signup />}></Route>
         </Routes>
       </AuthProvider>
     </Router>
  </div>
 </Container>
 )
}

export default App;

Home.js and Signup.js

import React from 'react'

export default function HomePage() {
  return (
    <div>This is the homepage</div>
  )
}

AuthContext.js and firebase.js

import React, { useContext, useState, useEffect } from 'react'
import { auth } from '../firebase'

const AuthContext = React.createContext()

export function useAuth() {
    return useContext(AuthContext)
}

export function AuthProvider({children}) {

    const [currentUser, setCurrentUser] = useState()
    const [loading, setLoading] = useState('true')

    function signup(email, password) {
        return auth.createUserWithEmailAndPassword(email, password)
    }

    useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged(user => {
            setCurrentUser(user)
            setLoading('false')
        })
    
        return unsubscribe

    }, [])

    const value = {
        currentUser,
        signup
    }

  return (
      <AuthContext.Provider value={value}>
          {!loading && children}
      </AuthContext.Provider>
  )
}

//------------------(firebase.js)---------------------

import firebase from 'firebase/compat/app'
import "firebase/compat/auth"

const app = firebase.initializeApp({
    apiKey: "***************************************",
    authDomain: process.env.REACT_AUTH_DOMAIN,
    projectId: process.env.REACT_PROJECT_ID,
    storageBucket: process.env.REACT_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_MESSAGING_SENDER_ID,
    appId: process.env.REACT_APP_ID
})

export const auth = app.auth()
export default app

I had to specify the key as a string because writing it as the other parameters didn't work

I've also tried using different versions of react-router, reading other answered questions, or writing the code differently. Nothing worked

4
  • I don't see any overt issue with the specific code you've shared in a snippet. I've copy/pasted it into a running codesandbox and it runs without issue. Do you see any errors in the browser's console? What debugging have you done? Commented Mar 14, 2022 at 15:34
  • The console contains the warnings shown in the attached image. I couldn't think of any way to debug (i'm very new to react), could you suggest me something? Thank you imgur.com/a/vwUAjkc Commented Mar 14, 2022 at 15:52
  • Those are only warnings. I suppose first check that App is rendering as you expect. Comment out the router and routes and render something trivial like <Container .......>Hello World!</Container>. Then incrementally add back in your UI elements/components until it breaks, then repeat the process for that element/component until you narrow it down to the offending element/component. Try that codesandbox to see if you can create a demo that reproduces the issue that we could inspect and debug live. Commented Mar 14, 2022 at 16:11
  • I tried to create a sandbox and everything works fine. The only difference from the original code is the lack of the part relating to integration with firebase, so I removed authcontext from the file and it worked. I am thinking that the problem is in that file, I changed the question and added the code contained in authcontext.js and firebase.js Commented Mar 14, 2022 at 16:57

1 Answer 1

1

Don't use strings "true" and "false" in lieu of actual boolean values. Non-empty strings are always truthy. Change your loading state from strings to booleans.

export function AuthProvider({ children }) {
  const [currentUser, setCurrentUser] = useState();
  const [loading, setLoading] = useState(true);

  function signup(email, password) {
    return auth.createUserWithEmailAndPassword(email, password);
  }

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged(user => {
       setCurrentUser(user);
       setLoading(false);
    });
    
    return unsubscribe;
  }, [])

  const value = {
    currentUser,
    signup
  };

  return (
    <AuthContext.Provider value={value}>
      {!loading && children}
    </AuthContext.Provider>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.