user8865657
user8865657

Reputation:

Why can't I read the variable in react-native

I am trying to access a variable in the render method. I have declared the variable outside the render function but inside the class definition. For some reason I cannot access the variable. It works if I declare the variable inside the render function.

import React, { Component } from 'react';
import { Text, View } from 'react-native';

export default class HelloWorldApp extends Component {
let a = "Random"
render() {

return (
  <View>
    <Text>{a}</Text>
  </View>
);
}
}

Upvotes: 0

Views: 993

Answers (2)

Asif vora
Asif vora

Reputation: 3359

Set variable in state and access that using this keyword this.state.a or you have to define it before your class as a constant or let or var.

 import React, { Component } from 'react';
    import { Text, View } from 'react-native';
    const a="random";

export default class HelloWorldApp extends Component {

   constructor (props){
      super (props);
        this.state={
              let a = "Random"
        }
   }

        render() {
            let {a}=this.state;

            return (
                <View>
                    <Text>{a}</Text>
                </View>
            );
        }
    }

Upvotes: 0

Phobos
Phobos

Reputation: 1646

You need to move your variable declaration into the render method. The declaration won't work otherwise.

render() {
    const a = "Random";
    return (
        <View>
            <Text>{a}</Text>
        </View>
    );
}

Upvotes: 1

Related Questions