0

I am unable to access class variable inside a function, following is my code:

export class MyClass extends React.Component<{}, {}>{
  public myArray: string[]; //I want to access this variable

  constructor() {
    this.state = { name: "" }
 } 
  private _hello = () => {
    console.log(this.state.name);
    console.log(this.myArray) //this lines throws undefined
  } 
    render(){
      <button onClick={this._hello}>Click</button>
    }

}
nbi
  • 1,276
  • 4
  • 16
  • 26

2 Answers2

0

Bring the function variable outside constructor. Btw render method should be outside constructor.

prisar
  • 3,041
  • 2
  • 26
  • 27
0

Try not to use private and public on react, here is some explanation, you could use:

const myArray: string[]; //I want to access this variable

export class MyClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
    }
  }

  hello = () => {
    console.log(this.state.name);
    console.log(myArray) //this lines throws undefined
  }

  render(){
    return (
      <button onClick={this.hello}>Click</button>
    )
  }
}

Pedro Vieira
  • 2,266
  • 1
  • 20
  • 35
  • @nbi What you want to do with the `myArray`? You could use it inside the hello function too – Pedro Vieira May 07 '19 at 17:03
  • this array will be populated by the values which will be coming from other components. As these value does not have any impact on the ui hence I haven't added to the state – nbi May 07 '19 at 18:07
  • You are right not adding them to states, to transfer data through components, you can use props and get it done – Pedro Vieira May 07 '19 at 18:27