Passing a button select choice back to previous screen

65 Views Asked by At

So after some research, I have learned how to make a button that will take the user to another screen, and provide them a text input where they can enter some words, then on pushing the done button take them back to the previous screen where what they typed will be displayed. But for my particular needs, I am trying to figure out how to instead of a text input have a selection of buttons, such as "large, medium, small" and have that button select the data that would be displayed instead, and return them to the previous page where it is displayed.

initial screen

function HomeScreen( route ) {
navigation = useNavigation();

React.useEffect(() => {
  if (route.params?.post) {
  }
}, [route.params?.post]);

return (
  <View>
    <Pressable
      title="Create post"
      onPress={() => navigation.navigate('CreatePost')}
    >
      <Text style={{ margin: 10 }}>Post: {route.params?.post}</Text>
    </Pressable
  </View>
);
}

button selection screen

function CreatePostScreen( route ) {
  const navigation = useNavigation();

  const [postText, setPostText] = React.useState('');

  return (
    <>
      <Pressable
        title="Done"
        onPress={() => {
          navigation.navigate({
            name: 'Home',
            params: { postText },
            merge: true,
          });
        }}
      >
        <Text>
          Large
        </Text>
      </Pressable>
    </>
  );
}

any insight is greatly appreciated.

1

There are 1 best solutions below

2
On BEST ANSWER

You can pass the data in form of object

{post: postText,
 buttonType: 'medium'}
      

For getting the data

 React.useEffect(() => {
    if (route.params?.post) {
     var buttonType= route.params?.buttonType
    }
  }, [route.params?.post]);

You can store the button type in a variable or state

var buttonType = route.params?.buttonType

Or You can try with useState() hooks

const [buttonType, setButtonType]=useState("")
setButtonType(route.params?.buttonType)

The for using it just do the following

<Text>{buttonType}</Text>

Please follow the React-Documentation