how to parse values from JSON.stringified data in a text component sent from a different page

1.1k views Asked by At

with regard to this tutorial "React Router Native - Passing Data" https://www.youtube.com/watch?v=SdOWxoH3HLg by @benawad user:4272160 I can't figure out how to extract bob or 5 from {"val1:"bob","val2":5} from the stringified string data in <Text>JSON.stringify(location.state)}</Text> when passing data between pages

I've tried to contact @benawad through a comment, I've searched google and here for similar but found nil relevant. I tried a regex unsuccessfully but there has to be a better way anyway...

code is at https://github.com/benawad/react-router-native-example/tree/1_advanced

// Home.js
import React from "react";
import { View, Text, Button } from "react-native";

export default ({ history }) => (
  <View>
    <Text>This is the home page</Text>
    <Button title="change page" onPress={() =>
    history.push("/products", {val1: "bob", val2: 5})
    />
  </View>
);


// Products.js
import React from "react";
import { View, Text, Button } from "react-native";

 export default ({ history, location }) => (
  <View>
  <Text>Product 1</Text>
  <Text>Product 2</Text>
  <Text>{JSON.stringify(location.state)}</Text>
  <Button title="change page" onPress={() => history.push("/")}/>
  </View>
);

I thought about trying to JSON.parse the stringified data. No joy. I tried location.state.val but just got

TypeError: undefined is not an object (evaluating 'location.state.val')
2

There are 2 answers

3
azundo On

You need to pass state through the history api. Change your Home component to

export default ({ history }) => (
  <View>
    <Text>This is the home page</Text>
    <Button title="change page" onPress={() => 
    history.push("/products", {val1: "bob", val2: 5)} />
  </View>
);

and then access location.state.val1 and location.state.val2 directly in your Products component.

See https://github.com/benawad/react-router-native-example/blob/1_advanced/ChangePageButton.js#L9 for the similar history line in the tutorial code.

The JSON.stringify used in the example code is just there as an illustration so that the entire location.state can be displayed in a Text element.

0
ravibagul91 On

You can pass props to history object,

<Button title="change page" 
  onPress={() => history.push({
    pathname: '/',
    state: { locationData: JSON.stringify(location.state) } //JSON.stringify needed if you want to pass object otherwise don't use.
  })}
/>

In the component which is rendered with / route, you can access the props like,

{JSON.parse(props.location.state.locationData)}        //Functional component
{JSON.parse(this.props.location.state.locationData)}   //Class based component

Note: JSON.parse needed if object is being passed otherwise no need to use.