Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a variable inside render() return - React Native

I am mapping json data and can console.log my result, but I can't insert those values in the render.

Here is the code I have for my render:

data_use = responseJson;
     const result_id = data_use.map(function(val) {
      return val.id;
    }).join(',');
    console.log(result_id);
render(){
return(

     <View style = { styles.MainContainer }>
      <View>
       <Card>          
          <View>
          <Text>{result_id}</Text>
         </View>
       </Card>
       </View>
     </View>
   );
  }

The error that I am getting is ReferenceError: result_id is not defined. Which is odd because it is defined?

like image 550
Laney Williams Avatar asked Sep 10 '25 07:09

Laney Williams


2 Answers

This approach will be useful if the data is loaded from a server.

constructor(props) {
  super(props);
  this.state = {
     data : []
  };

}

componentDidMount() {
   // Your code to fetch data from server

   this.setState({ data: your_array_from_fetch });
}

render(){
   return(
     <View style={ styles.MainContainer }>
        <View>
           <Card>          
              <View>
                {
                   this.state.data.length > 0 ?
                       this.state.data.map((val, index) => {
                           return (
                              <Text key={index}>val.id</Text>
                           );
                       } ).join(',');
                    : null
                 }
              </View>
           </Card>
         </View>
      </View>
  );
}

I made few assumption from my side and I believe this is what you want! If any issue write that down below.

EDIT:

  1. Yoganode issue can be fixed by testing if the data array length is greater than zero. This usually happens when render does not return anything.
  2. I used componentDidMount instead of componentWillMount because componentWillMount is deprecated.

Try this conditional render

{
    this.state.data.length > 0 ?
        this.state.data.map((val, index) => {
           if (some_var == another_var) {
              return (
                 <Text key={index}>val.id</Text>
              );
           }
        }).join(',');
    : null
}
like image 138
Rajendran Nadar Avatar answered Sep 13 '25 04:09

Rajendran Nadar


Everything you did is correct but variable you declared outside render? How can it be accessed in render

render(){
//considering array of objects in "data_use" state
 const result_id = this.state.data_use.map(function(val) {
      return val.id;
    }).join(',');

return(

     <View style = { styles.MainContainer }>
      <View>
       <Card>          
          <View>
          <Text>{result_id}</Text>
         </View>
       </Card>
       </View>
     </View>
   );
  }
like image 23
Revansiddh Avatar answered Sep 13 '25 02:09

Revansiddh