Accessing Array Inside Array With React

Tell us what’s happening:
I’m working on the Random Quote Machine. I created an array with several nested arrays acting as placeholders for quotes and their authors, which I am trying to separate by accessing the positions inside the nested array. However, this is causing an error. I’m not sure why, as this works using regular JavaScript, but if the first array value exists in component state, it doesn’t work.

Your code so far

Link to project:


import "./styles.css";
import React, { Component } from "react";
import { View } from "react-native";

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

export default class RandomQuoteMachine extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      generatedNumber: ""
    };
    this.generate = this.generate.bind(this);
  }
  generate() {
    this.setState({
      generatedNumber: Math.floor(Math.random() * 3)
    });
  }
  render() {
    const quotes = [
      ["author1", "quote1"],
      ["author2", "quote2"],
      ["author3", "quote3"]
    ];
    console.log(this.state.generatedNumber);
    const selectedQuote = quotes[this.state.generatedNumber][0];
    console.log(selectedQuote);
    return (
      <div id="quote-box">
        <div id="text">{selectedQuote}</div>
        <div id="author"></div>
        <button id="new-quote" onClick={this.generate}>
          New Quote
        </button>
      </div>
    );
  }
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15

Challenge: Build a Random Quote Machine

Link to the challenge:

What error is this causing? Please give as much details as possible

The error message is:

undefined is not an object (evaluating 'quotes[this.state.generatedNumber][0]')

There’s also a message in the console about error handling:

Consider adding an error boundary to your tree to customize error handling behavior.

Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries. 

    in Unknown

but that just seems like something you do in case an error is thrown, and wouldn’t actually fix the error, just fallback on other UI. However, if I am misinterpreting and this is the root issue, please let me know.

You may try removing the definition of quotes from inside render method, make it global

I’m still getting the same error.

What’s your code now?


import "./styles.css";
import React from "react";

const quotes = [
  ["author1", "quote1"],
  ["author2", "quote2"],
  ["author3", "quote3"]
];

export default class RandomQuoteMachine extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      generatedNumber: ""
    };
    this.generate = this.generate.bind(this);
  }
  generate() {
    this.setState({
      generatedNumber: Math.floor(Math.random() * 3)
    });
  }
  render() {
    
    console.log(this.state.generatedNumber);
    const selectedQuote = quotes[this.state.generatedNumber][0];
    console.log(selectedQuote);
    console.log(quotes[0][0], quotes[0][1], quotes[1][0], quotes[2][0]);
    return (
      <div id="quote-box">
        <div id="text">{selectedQuote}</div>
        <div id="author"></div>
        <button id="new-quote" onClick={this.generate}>
          New Quote
        </button>
      </div>
    );
  }
}

That is where the problem is. When the component is mounted, the value of this.state.generatedNumber is "". Therefore, the value of quotes[this.state.generatedNumber] is undefined initially. And undefined[0] throws an error.

You need to first initialize the value of this.state.generatedNumber with a valid index. For example, you can set its value to 0 initially and generate a random index in one of the life cycle methods.

1 Like

That worked, thanks!

Now I don’t understand why quotes[this.state.generatedNumber] doesn’t throw an error, though, since quotes[’’] is also undefined.

Undefined is a valid value, but you can’t try to get a property of undefined, because then you get the error

1 Like