Home > Back-end >  Pass state of username to profilepage?
Pass state of username to profilepage?

Time:11-11

(I'm a total beginner so I'm just trying to understand react) I've created an textinput and username/setUsername state that I want to save in a different component screen. By some reason I can't make it work, I've deleted all my tries and just posted the current code, can someone please guide me?

Start.js

const [username, setUsername] = useState("")

const changeHandler = (val) => {
    setUsername(val)}

const buttonPress = ()=> {
    console.log(username)
    navigation.navigate("Main")}


return (
<SafeAreaView style={styles.container}>
    <Text style={styles.text}>Enter name here</Text>
    <View style={styles.textinputarea}>
        <TextInput 
        style={styles.textinput}
        placeholder="Name here"
        maxLength = {12}
        onChangeText = {changeHandler}
        />
        <TouchableOpacity onPress={buttonPress}>
        <Ionicons name="checkmark-circle" size={40} color="white"/>
        </TouchableOpacity>
    </View>
</SafeAreaView>
);

}

And here is the part in Profile.js where I want to update the state when the "user" submits their name in Start.js

        <TouchableOpacity>
          <Title style={styles.text}>Hello {username}!</Title>
        </TouchableOpacity>

CodePudding user response:

In order to manage and pass around variables, you can do many things.

Assuming you are using react navigation library the recommended thing to do in my opinion is use navigation params.

Pass the username to the screen you are navigating as such:

navigation.navigate("Main", { username )

Get it and read it in the 'Main' screen as route (comes in props or you can use useRoute hook)

const {username} = route.params;

More on params in navigation - https://reactnavigation.org/docs/params/#what-should-be-in-params


Another way, already mentioned by DustInCompetent is to keep the state in a component, that's above the screens (where you set and where you get the variable).

Code example:

const [username, setUsername] = useState("")

return (
    <View>
     <Component1 username={username} setUsername={setUsername} />  
     <Component2 username={username} setUsername={setUsername} />
    </View>
);

However, I would not recommend this approach if you're using a navigation structure (like react-navigation) as you do not pass variables to screens there without breaking lazy loading, the only thing you normally pass is component. In a case, when you want to manage variables across multiple screens and components having a context helps. It helps solving the issue of passing variables around, but keep in mind, that if you scale to multiple contexts it's better to use Redux, Recoil or other state management tool. More on contexts can be found in React docs: https://reactjs.org/docs/context.html

Code example (App.js):

return (
<YourContext>
  <NavigationContainer>
      <Stack.Navigator>
       <Stack.Screen ... />  
       <Stack.Screen ... />  
      </Stack.Navigator>
  </NavigationContainer>
</YourContext>
);

Context file (Context.js):

import React, { createContext, useContext, useState } from 'react';

const UsernameContext = createContext();

export const UsernameProvider = ({ children }) => {
    const [username, setUsername] = useState();

    return (
        <UsernameContext.Provider
            value={{
                username,
                setUsername,
            }}
        >
            {children}
        </UsernameContext.Provider>
    );
};

export const useUsernameProvider = () => useContext(UsernameContext);

export default UsernameContext;

Then you can import and use context in every screen/component you need like:

const { username, setUsername } = useUsernameProvider();

CodePudding user response:

This article is about sharing state between different components without any complex React Context/Redux techniques. So it is good for beginners! Short and informative.

You will need to have a component that will be responsible for rendering the Start and Profile components. Let's say, an App.js or any other component ( Layout.js ).


Move

const [username, setUsername] = useState("")

to the Layout.js / App.js, and pass it down as a prop like

<Start username={ username } setUsername={ setUsername } />

Also pass value prop to the TextInput component.

So that state that gets updated by onChangeText actually updates the input's value., not only the state variable, but the component.

<TextInput 
        value={ username }
        style={styles.textinput}
        placeholder="Name here"
        maxLength = {12}
        onChangeText = {changeHandler}
        />
  • Related