can not access to my state using map in react - reactjs

I have a state and I want use map to go through it,
function App() {
const [cardlayouts,setCardLayouts]=useState({id:"1",title:"title1",img:{pic1},text:"text1"})
return (
<div className="App">
{
cardlayouts.map(s=><CardLayout id={s.id} title={s.title} img={s.img} text={s.text}/>)
}
</div>
);
}
I get an error which says cardlayouts.map is not a function,any idea?

This is because you are trying map on the object. Your cardlayouts is object. You can use map only on array

Edit your code like this. To map you should have an array. But you have given a object instead.
const [cardlayouts, setCardLayouts] = useState([{id:"1",title:"title1",img:
{pic1},text:"text1"}])

.map() is an array method, but your state isn't an array.
You don't need to use map in this situation. Just access the keys like normal:
function App() {
const [cardlayouts,setCardLayouts] = useState({
id:"1",
title:"title1",
img:{pic1},
text:"text1"
})
return (
<div className="App">
<CardLayout
id={cardlayouts.id}
title={cardlayoust.title}
img={card.img}
text={s.text}
/>
</div>
);
}
Or, make the state an array and map over it like this:
function App() {
const [cardlayouts,setCardLayouts] = useState([
{
id:"1",
title:"title1",
img:{pic1},
text:"text1"
}
])
return (
<div className="App">
{cardlayouts.map(layout => (
<CardLayout
id={layout.id}
title={layout.title}
img={layout.img}
text={layout.text}
/>
))}
</div>
);
}

Related

I am not getting data of my useState through .map function in React Js

React Js
I am trying to display data through .map which is in react state object, but I am not getting data on browser with any error, yes I now that I am not write setState in this code because i want only display my data on my browser. if this problem will be solved then I will done my setState, I Think setState is not necessary for only showing data which is in State Object.
import React from 'react';
import TinderCard from 'react-tinder-card';
function TinderCards(){
const [people, setPeople] = React.useState([
{
name: 'steve jobs',
url: 'https://cdn.britannica.com/04/171104-050-AEFE3141/Steve-Jobs-iPhone-2010.jpg'
},
{
name: 'mark zukerberg',
url: 'https://cdn.britannica.com/54/187354-050-BE0530AF/Mark-Zuckerberg.jpg'
}
]);
return (
<div>
{
people.map(person =>{
<h1>{person.name}</h1>
})
}
</div>
)
// const people = [] same thing
// BAD
// const people = [];
// people.push('sonny', 'qazi')
// GOOD (push to an array in REACT)
// setPeople([...people, 'mathan', 'lal'])
}
export default TinderCards;
You don’t return anything from map.
Change your return section to this:
return (
<div>
{people.map(person => (
<h1>{person.name}</h1>
))}
</div>
)
or if you like to keep the curly brackets syntax:
return (
<div>
{people.map(person => {
return <h1>{person.name}</h1>
})}
</div>
)

Cannot return the content from a nested array in React JS

I am trying to display the data I fetched from an API which is a nested array. The json file looks like this for one pool and the devices inside that pool:
[
{
"id": "staging",
"pool": "some name",
"status": "FAILED",
"deviceMonitoringEntries": [
{
"deviceDescriptor":{
"id": "Apple_TV_HD1",
}
]
}
]
I want to display the id of the pool first and then display the devices assigned to the pool by displaying the id in deviceDescriptor.
My code is like this:
import React, { useEffect, useState } from 'react'
import axios from 'axios'
function Pool(){
const url = 'http://localhost:8043/pools'
const [pool, setPool] = useState(null)
let content = null
useEffect(() => {
axios.get(url)
.then(response =>{
setPool(response.data)
})
}, [url])
if(pool){
console.log("in if pool")
console.log(pool)
return (
content=
<>
{pool.map((id) => {
<h3 key = {id}>{id}</h3>
return (
<>{pool.map(({ deviceMonitoringEntries}) => (
deviceMonitoringEntries.map((deviceDescriptor) => (
<p key = {deviceDescriptor.id}> {deviceDescriptor.id}</p>
))
))}</>
);
})}
</>
)
}
return(
<div>
{content}
</div>
)
}
export default Pool
However, the header <h3 key = {id}>{id}</h3> never prints. I can display the header and paragraph separately but it does not work together. I am very new to React and I would appreciate your help!
As per React documentation
React components implement a render() method that takes input data and returns what to display.
In the functional component, you directly add a return statement at the end.
You cannot assign variables like this in your code.
return (
content=
<>
...
</>
You got the response and you stored that value in a state variable. Use the variable and render your content in the final return statement.
{
pool.map((p) => (
<>
<h3 key={p.id}>{p.id}</h3>
{p.deviceMonitoringEntries.map((device) => (
<p key={device?.deviceDescriptor?.id}>{device.deviceDescriptor?.id}</p>
))}
</>
));
}
You can try like that in your code and I am attaching a sandbox for reference here.

List all items in an array in ReactJS

This is the file that I'm rendering in App.js:
ProductList.js
import React from 'react'
export default function ProductList() {
var items = JSON.parse(localStorage.getItem("products")); //[foo: "4.43", bar: "3.25"]
const listitems = () => {
for( var p in items) {
<p>{p}, {items[p]}</p>
}
}
return (
<div>
{listitems}
</div>
);
}
This does not output anthing.
The question is: how do I list all the items in an array like "foo, 4.43"...?
return (
{items.map((el) => (
<p>{el}</p>
)}
)
I guess there are a few issues with this code.
First, the products you are getting from localStorage is an array, so you won't be able to get the key:value pair of it.
You would be better off transforming the products into an object, like:
{
foo: "4.43",
bar: "3.25"
}
Then, one alternative is to get the keys by doing const productKeys = Object.keys(products). Then map through them and display the values as well:
const listItems = productKeys.map(key => <p>{key}: {products[key]}</p>)
return {
<div>
{listItems}
</div>
}

Element not being found

I am having an issue where I have an element, but I cannot seem to reference it without getting a null error.
render() {
const getXandY = () => {
const elment = document.getElementById("test");
const xpos = elment.style.left;
const ypos = elment.style.top;
console.log(xpos);
console.log(ypos);
};
return (
getXandY(),
(
<div id="test" className="treeContainer">
{this.state.configs.map((config) => (
<div>
<Configs configName={config.name} configNumber={config.id} />
</div>
))}
</div>
)
);
}
}
any help is appreciated.
I'm not sue you understand React. In render() function try to avoid defining functions, it's a function for just returning the JSX you want to render (you can't return nothing else there). So define your getXandY outside render(). If you really want to invoke it on rendering, simply put the function call inside, that's it. So it would look something like:
const getXandY = ...
render() {
getXandY();
return (
<div ... />
);
{

How to fix the error "react use hook cannot be called inside a callback function" using react?

i am using useHook named useGetCompanyByItemId in the return statement.
and so i am getting the error
"react hook cannot be called in a callback function"
what i am trying to do?
i am querying for owneditems and shareditems.
and i display both the items. in the Content div i do mapping and there i am calling the useGetCompanyByItemId hook and i get the error.
below is my code,
function Parent() {
const ownedItems = [{ //somearray of objects}];
const sharedItems = [{//somearray of objects}];
const getCurrentItems = () => {
return ownedItems.concat(sharedItems);
}
return (
<Wrapper>
{getCurrentItems.length> 0 &&
<FirstWrapper>
//somedivs
</FirstWrapper>
<Content>
{springProps.map((index) => {
const item = getCurrentItems()[index];
const isSharedItem = item && item.cognitoId !== cognitoId;
const company = useGetCompanyByItemId(item.id); //here is the error
return (
<>
{isSharedItem &&
<div>
<span>company</span>
</div>
}
</>
}
)
}
);
</Content>
</Wrapper>
);
}
i am not sure how to fix this. i need to pass the item.id for the useGetCompanyById hook and i dont know how to pass that item.id from outside the return statement since that would fix that error.
could someone help me fix this error. thanks.
Extract this logic to a component
function Item({ item, isSharedItem }) {
const company = useGetCompanyByItemId(item.id);
return (
<>
{isSharedItem && (
<div>
<span>company</span>
</div>
)}
</>
);
}
and then use it in your loop
springProps.map((index) => {
...
return <Item item={item} isSharedItem={isSharedItem} key={index} />
I can see two ways of refactoring here:
Option 1: If you dont have control over the custom hook to modify
Extract the iteration into a component:
const Company = ({itemId, isSharedItem}) => {
const company = useGetCompanyByItemId(itemId);
return (<>
{isSharedItem &&
(<div>
<span>{company}</span>
</div>)
}
</>);
}
Use the above component while you iterate.
Option 2: If you have control over the custom hook:
I would recommend to refactor custom hook to return a method than object. Sample usage:
const {getCompanyByItemId} = useFetchCompany();
.
.
.
anywhere in the code,
getCompanyByItemId(itemId)
Obvious advantage with above option:
Readable and extendable and use it anywhere and even pass around
You don't have to worry about refactoring and code splitting just not to break hook rules(do so if it makes sense ofcourse).

Resources