New to React Native and trying to figure out the right way to access props from another screen.
Most of the answers I found online were all very different, so I'm wondering if there's a recommended way to do it.
App.js - Here user is the currently connected user's data.
{ user ? (
<Stack.Screen name="Home">
{props => <HomeScreen {...props} extraData={user} />}
</Stack.Screen>
) : (...)
}
On other screens, I'm sending the user to HomeScreen this way:
navigation.navigate('Home', {user: user})
HomeScreen.js - In this function, I want to access the user's data from App.js, or any other screen that sends the user.
export default function HomeScreen(props, {navigation}) {...}
How should I structure my code in HomeScreen.js to receive the user correctly?
I'd recommend using Context API, documentation about that can be found here
Here's an example usage:
Create a provider for the user details
// Import createContext from react
import {createContext} from 'react'
// Create a context that holds a user and a function to change the user details
export const UserContext = createContext({user: null, setUser: (user) => {}})
Wrap the main navigator that contains your home screen with the provider from UserContext
function MainNavigator() {
// For state management, useState for the user
const [user, setUser] = useState(null)
return (
// Pass the user and setUser inside the Provider value for consumption
<UserContext.Provider value={{user, setUser}}>
<YourNavigator>
{ /* Your screen */ }
<Stack.Screen name="home" component={HomeScreen} />
</YourNavigator>
</UserContext.Provider>
)
}
Consume the context inside your HomeScreen component using a simple hook
import { useContext } from 'react'
import { UserContext } from '../where/your/provider/is'
export default function HomeScreen(props) {
// Consume the context!
const { user, setUser } = useContext(UserContext)
return <>{ /* Your screen layout */}</>
}
This is just a simple example for this particular use case, I suggest learning more about Context API and play around with it
Hope you find this helpful