Fundamental React question

Hi , I know I am just forgetting something fundamental about React here but I’ve been circling this problem for too long now:

I want to print the data that is returned from generateRandomCard() but when I click on button, nothing shows up. A couple of console.logs in generateRandomCard() showed correct values so that’s OK.

Code:

import React, { Component } from "react";

class FlashCard extends Component {


  state = {

    data: [

     //a bunch of arrays

    ]

  };

  generateRandomCard = () => {

    let randomNumber = Math.floor(Math.random() * Math.floor(9));

    let randomCard = this.state.data[randomNumber];

  };

  render() {

    console.log(this.randomCard);

    return (

      <React.Fragment>

        <div id="selections" className="row">

          <div className="col-md-6">

            <select className="form-control form-control-sm">

              <option value="makeChoice">

                I want to test my knowledge of....

              </option>

              <option value="urduFront">Nastaleeq</option>

              <option value="urduFront">Romanized</option>

              <option value="urduFront">Translation</option>

            </select>

          </div>

        </div>

        <div className="card">

          <div className="card-body">

            <h6>{this.randomCard}</h6>

          </div>

        </div>

        <button onClick={this.generateRandomCard}>Generate New Card</button>

      </React.Fragment>

    );

  }

}

export default FlashCard;

@sabbyiqbal
you cant access this because it is inside a function, you should have randomCard as state instead and the use setState to add your random card to it, only state will re render the page

1 Like

For reference have a look at React API documentation about updating:

An update can be caused by changes to props or state.

So this.randomCard needs to be in some sort of state or prop if you want React to reflect its updating values.
Hope this helps :+1:

1 Like

The method generateRandomCard doesn’t do anything.
It just storing the value into a variable.
If you want to access randomCard correctly, then as @biscuitmanz said, put it on the state, then when you called getRandomCard() use setState to change the value.
One more thing, for randomNumber you can do:
let randomNumber = Math.floor(Math.random() * 9) or
let randomNumber = Math.floor(Math.random() * this.state.data.length)

2 Likes