Ad

How To Select Random Object From Array With React Hooks?

- 1 answer

I don't know why my function not working. I won't to display random citites from array? But if I click button then show me

Error -:

AppHooks.js:15 Uncaught 
TypeError: Cannot read property 'length' of undefined.`

What I do wrong?

import React, {useState} from 'react';


export default function AppHooks () {
    const [cities, setCities] = useState([
        {
            nameCity: 'Kraków'
        },
        {
            nameCity: "Kielce"
        }
    ])

    function randomCities (e, cities) {
        let len = cities.length;
        // let randCiti = cities[Math.floor(Math.random() * cities.length)];
        setCities(cities[Math.floor(Math.random() * len)]);
        return cities
    }
    let citi = cities.map((cit, i) => {
        return(
        <div key={i}>
            {cit.nameCity}
        </div>)
        }
    )

    console.log(cities[0]);
    return(
        <div>
            {citi}
            <button onClick={randomCities}> Change</button>
        </div>

    )
}
Ad

Answer

If you want to have a random city from your array I would design the app different and just set the index to select from.

Also if you are using fat arrow functions there is no need to pass the cities to the click event-handler. I created a small example for you.

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

function AppHooks() {
  const cities = [
    {
      nameCity: "Kraków"
    },
    {
      nameCity: "Kielce"
    }
  ];

  const [activeCity, setActiveCity] = useState(0);

  const randomCities = e => {
    const len = cities.length;
    setActiveCity(Math.floor(Math.random() * len));
  };

  return (
    <>
      <div>{cities[activeCity].nameCity}</div>
      <button onClick={randomCities}> Change</button>
    </>
  );
}

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

CodeSandbox - Example

Ad
source: stackoverflow.com
Ad