Así que estoy tratando de cambiar un parámetro de objeto que está siendo llamado por .map dentro de llaves. Aquí está el código:
import React, { useEffect, useState } from 'react' function App() { const [news, setNews] = useState([]) const [searchQuery, setSearchQuery] = useState('city') const getNews = () => { fetch('https://api.randomuser.me/?nat=USA&results=5') .then(result => result.json()) .then(data => setNews(data.results)) .then(error => console.log(error)) } const handSearch = (e) => { setSearchQuery(e.target.value) } //the [] at the end is enabled to request data only onces useEffect(() => { getNews() }, [searchQuery]) return ( <div> <form> <input onChange={handSearch}></input> </form> <p><b>Available Input: </b>city, state, country, postcode</p> <hr/> { news.map((value, index) => ( <p key={index}>{`value.location.${searchQuery}`}</p> )) } <p>{searchQuery}</p> </div> ); } export default App;Pero no funciona, solo devuelve una cadena. He intentado:
``[]return() solo para value.location.${searchQuery} y vuelva a ponerla en las llaves ¿Cómo completar un parámetro de objeto por ${} ?
Cualquier ayuda sería apreciada, gracias antes!
cambia esta línea de tu código
<p key={index}>{`value.location.${searchQuery}`}</p>a esto
<p key={index}>{value.location[searchQuery]}</p>va a funcionar
lee este artículo clave dinámica que te ayudará.
Debe usar corchetes para obtener el valor calculado de searchQuery value.location[searchQuery]
Por ejemplo:
import React, { useEffect, useState } from 'react'; function App() { const [news, setNews] = useState([]) const [searchQuery, setSearchQuery] = useState('city') const getNews = () => { fetch('https://api.randomuser.me/?nat=USA&results=5') .then(result => result.json()) .then(data => setNews(data.results)) .then(error => console.log(error)) } const handSearch = (e) => { setSearchQuery(e.target.value) } //the [] at the end is enabled to request data only onces useEffect(() => { getNews() }, [searchQuery]) return ( <div> <form> <input onChange={handSearch}></input> </form> <p><b>Available Input: </b>city, state, country, postcode</p> <hr/> { news.map((value, index) => ( <p key={index}>{value.location[searchQuery]}</p> )) } <p>{searchQuery}</p> </div> ); } export default App;