In React Hooks. How to set state to a random number and use that to display a string from an array

Viewed 5679

Hi I'm doing a course to learn React Hooks and i'm stuck on a task. My task is to create a button that onClick displays a random quote from this array.

const App = (props) => {
  const [selected, setSelected] = useState(0)

  return (
    <div>
      {props.anecdotes[selected]}
    </div>
  )
}

const anecdotes = [
  'If it hurts, do it more often',
  'Adding manpower to a late software project makes it later!',
  'The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
  'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
  'Premature optimization is the root of all evil.',
  'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.'
]

ReactDOM.render(
  <App anecdotes={anecdotes} />,
  document.getElementById('root')
)

I have tried to solve this myself however I encounter errors. Wondered if someone had an easy explanation for this? Thanks

This is the error I keep on receiving.

TypeError: Cannot read property '0' of undefined App src/App.js:14 11 | 12 | return ( 13 |

14 | Get Random | ^ 15 | {anecdotes[selected]} 16 | 17 | )

4 Answers

Solution of hooks to pick random value from array

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

function Example(props) {

  const [count, setCount] = useState(0);

  const { anecdotes } = props;
  return (
    <div>
      <p>You clicked and random value from array: <h4>{count}</h4></p>
      <button onClick={() => setCount(anecdotes[Math.floor(Math.random()*anecdotes.length)])}>
        Click me
      </button>
    </div>
  );
}
ReactDOM.render(
  <Example  anecdotes={[1,4,3,2,8,5]}/>,
  document.getElementById('root')
);

Hooks to pick random value from array

So, your App Component receives the quotes, shows the current one already, and based on the selected you want to have a new quote.

The only thing you have to do is to add a button that changes the selected value via setSelected like so; https://codesandbox.io/s/hungry-dream-4b3eg

The useState hook provides you 2 arguments, the first one, is to read your state, the second one is to write your state.

I'm not going to spoiler everything since your are taking a course :) So make the number random, maybe with a additional method, and you will have your expected behaviour.

const App = props => {
  const [selected, setSelected] = useState(0);

  return (
    <div>
      <button onClick={() => setSelected(4)}>change quote</button> // <=== this addition
      {props.anecdotes[selected]}
    </div>
  );
};

All you need to is generate a random number between 0 and length -1 of the anectodes array.

const App = ({anecdotes}) => {
  const [selected, setSelected] = useState(0)

  const handleClick = () => {
      const randomNumber = Math.floor(Math.random() * anecdotes.length);
      setSelected(randomNumber);
  }

  return (
    <div>
      <button onClick={handleClick} >Get Random</button>
      {anecdotes[selected]}
    </div>
  )
}

https://codesandbox.io/s/blissful-hofstadter-mr01k

Random Component:

import React, {  useState } from "react";

import "./styles.css";

const anecdotes = [
  'If it hurts, do it more often',
  'Adding manpower to a late software project makes it later!',
  'The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
  'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
  'Premature optimization is the root of all evil.',
  'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.'
]

export default function showRandom() {
  const [selected, setSelected]=useState(0);
  return (
    <div className="App">
    <h1> {anecdotes[selected]}</h1>
     <button onClick={()=>setSelected(Math.floor(Math.random() * `anecdotes.length))}>Show Random </button>`
      </div>
  );
}

App Component:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import Random from "./showRandom";
function App() {
  return (
    <div className="App">
     <Random /></div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Related