Undefined is not an object (evaluating this.props.route.params.text)

Viewed 88

I followed React Navigation Doc to pass params to my previous screen, but i'm getting error when acces it in my previous screen saying

evaluating this.props.route.params.text

export default class SelectMap extends Component{
    constructor() {
        super()
      }
    render(){
        const {text} = this.props.route.params
        return (
            <View style={{alignItems: 'center', justifyContent:'center'}}>
                <TouchableOpacity onPress={() => this.props.navigation.navigate('MapView')}>
                    <Text>
                        Open Maps
                    </Text>
                    <Text>
                        {text}
                    </Text>
                    
                </TouchableOpacity>       
            </View>
        )
    }
}

This is how i sent the params

this.props.navigation.navigate('SelectMap', {text:JSON.stringify(this.state.marker)})
2 Answers

I guess it's because this code const {text} = this.props.route.params didn't run when you navigate back to your previous screen

I think you can use callback function instead

export default class SelectMap extends Component{
    constructor() {
        super()
      }
    render(){
        const [text, setText] = useState(""); // change to state
        return (
            <View style={{alignItems: 'center', justifyContent:'center'}}>
                <TouchableOpacity onPress={() => 
// use callback
this.props.navigation.navigate('MapView', { onTextSelect: (text) => {
                    setText(text)
                } })}>
                    <Text>
                        Open Maps
                    </Text>
                    <Text>
                        {text}
                    </Text>
                    
                </TouchableOpacity>       
            </View>
        )
    }
}

your constructor must be as below

constructor(props) {
  super(props);
}
Related