Ad
How To Select Random Object From Array With React Hooks?
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);
Ad
source: stackoverflow.com
Related Questions
- → How do I create an array from a single form input box with php on octobercms?
- → Print the output value of an array in twig [OctoberCMS]
- → Declare an array variable to the controller/component [Laravel, October CMS]
- → Removing a JavaScript property inside a specific Object within an Array
- → Javascript loop indexing issue
- → search array without duplicates React.js
- → Populating array with items from different HTML attributes
- → Get all index value of 1 from binary "01000111"
- → Remove objects from array - Two different approaches, two different results when consulting the length of each array
- → Compare values in two arrays
- → adding multiple polygons in google maps using loops and arrays
- → .split() JS not "splitting" correctly?
- → Vue.js - Binding radio elements of same name to array
Ad