React JS, Error is not defined no-undef when attempting to obtain first value from array

1.7k views Asked by At

Am attempting to output a value from an array, but get the error: array1 is not defined no-undef

Code Snippet:

 constructor() {
        super();
        this.state = {  
          array1: [],
        }
      }

//code snippet componentDidMount:

componentDidMount(props) {
    this.setState({array1: [5, 12, 8, 130, 44] })
  }

//code snippet, function:

found = this.state.array1.find((element) => {
    return element > 10;
  }); 

code snippet:

render(){
console.log(found);
}

the page errors out in the arrow function, Could I get some help please?

2

There are 2 answers

4
Vikas On BEST ANSWER

Your constructor should be changed to

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

You haven't defined your array1 as a state.

Update (Updated answer based on comments)

constructor() {
    super();
    this.state = {
        array1: []
    }
    this.found = this.found.bind(this);
}

found() {
    return this.state.array1.find((element) => {
        return element > 10;
    }); 
}

render(){
    console.log(this.found());
}
0
devserkan On

Without constructor, without binding your function (thanks to class-fields) here is how you render (not console.log) array elements.

class Foo extends React.Component {
  state = { array: [] };
      
  componentDidMount() {
    this.setState({array: [5, 12, 8, 130, 44] })
  }
  
  // With some cheating.
  found = () =>
    this.state.array
    .map(el => el < 10 ? undefined : <p>{el}</p> );    
  
  // Maybe nicer one?
  foundAlternative = () => 
    this.state.array
      .filter( el => el > 10 )
      .map( el => <p>{el}</p>);
      
       
  render() {
    return (
      <div>{this.found()}</div>
    )
  }

}

ReactDOM.render(
  <Foo />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>