'Props lost after navigate and cloneElement

In an app I'm currently working on, the authentification has been done like this, to pass user's data into children components (in App.js, I would have rather used useContext to access user data in whatever component) [App.js]:

const RequireAuth = ({ children }) => {

    // fetch user data from database, ...

    return <>{React.cloneElement(children, { user: {...user, ...userExtraData} })}</>;

};

Then, an example of a Route is specified as [App.js]:

 <Route
      path="/addgame"
      element={
              <RequireAuth>
                  <FormAddGame />
              </RequireAuth>

            }
           
  />

However, my current problem is the following:

From a ComponentA, I want to navigate to /addgame (=FormAddGame component, see below) while setting an existingGame prop. Thus, I use [ComponentA.js]:

let navigate = useNavigate()    
navigate('addgame', { existingGame: game })

The said FormAddGame component is [FormAddGame.js]:

function FormAddGame({ user }) {

    const { existingGame } = useLocation()

    console.log(existingGame)
    ...
}
export default FormAddGame;

However, while I correctly navigate to /addgame, the existingGame prop stays undefined once in FormAddGame while it should be not (as game is not undefined)



Solution 1:[1]

Try passing props like this:

navigate("addgame", { state: { existingGame: game } });

and destructure like this:

const { state: { existingGame } = {} } = useLocation();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mujeeb Qureshi