map in react not displaying data with { } (curly brackets) - javascript

So I am trying to return the data from API by map and when I am using ( ) these brackets I am getting the data when I use { } to put if statement, I am getting nothing on my web page but still getting the data in console
const Addtocart = () => {
const data = useSelector((state) => state);
console.log("products", data.productData);
const dispatch = useDispatch();
useEffect(() => {
dispatch(productList());
}, []);
return (
<div id="addtocart-info">
<div className="products">
{data.productData.map((item) => { // here this bracket
if (item.id % 2 === 0 || item.id === 0) {
<div key={item.id} className="product-item">
<img src={item.photo} alt="" />
<div>Name : {item.name} </div>
<div>Color : {item.color} </div>
<button onClick={() => dispatch(addToCart(item))}>
ADD to Cart
</button>
</div>;
console.warn(item.id);
} else {
console.log(item.id);
}
})}
</div>
</div>
);
};
export default Addtocart;
Is there any way to put if statement with () or make this work

You are not getting anything because when u use {} you have to use a return keyword, but when you are using () you don't have to use a return keyword because the whole code inside this is considered as a single piece of code even if it's distributed in multiple lines
so change your code to ,
{data.productData.map((item) => { // here this bracket
if (item.id % 2 === 0 || item.id === 0) {
return (
<div key={item.id} className="product-item">
<img src={item.photo} alt="" />
<div>Name : {item.name} </div>
<div>Color : {item.color} </div>
<button onClick={() => dispatch(addToCart(item))}>
ADD to Cart
</button>
</div>
)
} else {
console.log(item.id);
}
})}

If you use curly brackets you also need to use a return statement. Basically if you don't use curly brackets in an arrow function the statement is returned automatically.
Example:
let x = someArray.map(x => x*2); // returns a new array with the expression applied
let x = someArray.map(x => {return x * 2}) // use the return here

Related

map is not a function returning div inside ternary operator

I'm trying to do a little react app pulling some uniswap crypto data for my own UI just for fun, I've grabbed some data with a graphql query and I'm trying to render it out on the condition that its loaded which I get from a ternary operator in my functional component.
when I try this in multiple combinations, I just get the error that allTokenData.map is not a function
I have included my component below and I have notated where my mapping function is trying to pull data from the array I get back from graphql, since I'm getting data I'm sure I'm just mixing something up with the mapping syntax :/
here is a snippet of the data I'm grabbing for reference logged in the console, any help is appreciated
function CoinData(props) {
//fetch whichever coin we want to add
const NEWCOIN_QUERY = gql`
query tokens($tokenAddress: Bytes!) {
tokens(where: { id: $tokenAddress }) {
derivedETH
totalLiquidity
}
}
`;
const { loading: ethLoading, data: ethPriceData } = useQuery(ETH_PRICE_QUERY);
const { loading: allLoading, data: allTokenData } = useQuery(QUERY_ALL_TOKENS);
const { loading: coinLoading, data: coindata } = useQuery(NEWCOIN_QUERY, {
variables: {
tokenAddress: props.parentState.newcoins!== '' ? props.parentState.newcoins.toString() : '0x6b175474e89094c44da98b954eedeac495271d0f',
},
});
const coinPriceInEth = coindata && coindata.tokens[0].derivedETH;
const coinTotalLiquidity = coindata && coindata.tokens[0].totalLiquidity;
const ethPriceInUSD = ethPriceData && ethPriceData.bundles[0].ethPrice;
console.log(props.parentState.newcoins)
return (
<div>
<div>
coin price:{" "}
{ethLoading || coinLoading
? "Loading token data..."
: "$" +
// parse responses as floats and fix to 2 decimals
(parseFloat(coinPriceInEth) * parseFloat(ethPriceInUSD)).toFixed(2)}
</div>
<div>
Coin total liquidity:{" "}
{coinLoading ? "Loading token data...": parseFloat(coinTotalLiquidity).toFixed(0)}
</div>
<div>
</div>
<div>
//////////////////////////////////////////----map function////////////////////////////
{allLoading ? "Loading token data...":
<div>
{allTokenData.map((token, index) => (
<p key={index}> {token.id} SYN: {token.symbol}</p>
))}
</div>
}
//////////////////////////////////////////----map function////////////////////////////
</div>
</div>
);
}
maybe allTokenData.tokens.map.
It is because allTokenData is an object.
const {tokens} = allTokenData
{tokens.map((token, index) => (
<p key={index}> {token.id} SYN: {token.symbol}</p>
))}

React: Rendering a method defined inside arrow function?

Hello friends! I hope you are well.
I've got an arrow function called WorldInfo and its parent component is passing down an object in props that for the sake of this example, I'm just calling object. Now In WorldInfo I also want to parse and list the items in object, so I've created the method serverInfoTabList to take object and shove it through .map. My problem is when compiled, my browser does not recognize serverInfoTabList either when it's defined nor called in WorldInfo's own return function.
Here is the error and the code itself.
Line 7:5: 'serverInfoTabList' is not defined no-undef
Line 34:22: 'serverInfoTabList' is not defined no-undef
const WorldInfo = (props) => {
serverInfoTabList = (object) => {
if (object != undefined){
return object.item.map((item) => {
const time = Math.trunc(item.time/60)
return (
<li key={item._id}>{item.name}
<br/>
Minutes Online: {time}
</li>
);
});
}
}
return (
props.object!= undefined ?
<div className={props.className}>
<h1>{props.world.map}</h1>
{/* <img src={props.object.image}/> */}
<div>
<ul>
{serverInfoTabList(props.object)}
</ul>
</div>
</div>
:
null
);
}
Thanks for your time friendos!
You forgot the const declaration
const serverInfoTabList = (object) => {
/* ... */
}
The other problem is that you're accessing properties which doesn't exist props.world for instance. Also you're mapping through an undefined property props.object.item. I've corrected your sandbox
const WorldInfo = props => {
const serverInfoTabList = object => {
return Object.keys(object).map(key => {
const item = object[key];
const time = Math.trunc(item.time / 60);
return (
<li key={item._id}>
{item.name}
<br />
Minutes Online: {time}
</li>
);
});
};
return props.object ? (
<div className={props.className}>
<h1>{props.world.map}</h1>
{/* <img src={props.object.image}/> */}
<div>
<ul>{serverInfoTabList(props.object)}</ul>
</div>
</div>
) : null;
};
class Todo extends Component {
render() {
const object = { item1: { _id: 1, time: 1 }, Item2: { _id: 2, time: 2 } };
return (
<div>
<WorldInfo object={object} world={{ map: "foo" }} />
</div>
);
}
}

ES6 map function for tuples/2d arrays

I'm trying to write a map function to return a navbar.
I have an array/dictionary that I want to loop through using the map function that looks something like
[['Text', './link.html'],
['Text2', './link2.html'],
['Text3', './link3.html']]
or else
{'Text', './link.html',
'Text2', './link2.html',
'Text3', './link3.html'}
Whatever type I need to loop through doesn't matter, I just want to loop through sets of 2, ideally I'd want to use tuples, but it doesn't look like that's an option from what I've read.
When looking at solutions that use the dict/object method, I don't know how to access both the key and the value. For ex.
var NavBar = (props) => {
return (
<div id="NavMain">
{Object.keys(props.links).map((link,index) => {
return <NavBarItem link={link} />
{/* Where do I access the key? */}
})}
</div>
)}
If I try to map this as a 2d array, my IDE is showing some error lines underneath 'row', 'text' and '/>' in the code below
var NavBar = () => {
return (
<div id="NavMain">
{this.props.links.map((row,index) => {
return <NavBarItem link=row[1] text=row[0] />
})}
</div>
)}
Other solutions I've looked up are really messy. I'm wondering if there's a clean way to use the map function over sets of 2.
You can use array destructuring inside the .map() like this:
So assuming you have a data set of an array of arrays:
const arr = [
['Text', './link.html'],
['Text2', './link2.html'],
['Text3', './link3.html']
]
var NavBar = (props) => {
return(
<div id="NavMain">
{arr.map(([text, link]) => {
return <NavbarItem link={link} text={text}/>
})}
</div>
)
}
We know the first item is text and the second item is link as expected.
See sandbox for working example: https://codesandbox.io/s/stoic-payne-9zdp3
You almost had it. Try this:
/*
props.links = {
'Text' : './link.html',
'Text2' : './link2.html',
'Text3' : './link3.html'
}
*/
var NavBar = (props) => {
return (
<div id="NavMain">
{Object.keys(props.links).map((key, index) => {
return <NavBarItem link={props.links[key]} text={key} />
})}
</div>
)
}

Curly braces inside curly braces in React

I have presentational component in React. And with products.some i am trying to check if any item inside products is checked. And if some item is checked, render parent block for RequestedProduct component. I know that the problem is a second pair of curly braces as React think it's a prop. Is there another way to do this?
const Requested = ({ products, getCurrentTime }) => (
<div className="pepper-pin-body-tab requested-tab">
<div className="pepper-pin-body-tab-title">
Запрошенные
</div>
<div className="pepper-pin-body-tab-indicator" />
{products.some(product => product.checked) ? (
<div className="requested-tab-list-requested">
<div className="requested-tab-list-requested-time">
{getCurrentTime()}
</div>
{products.filter((product, key) => {
if (product.checked) {
return (
<RequestedProduct
key={key}
title={product.title}
/>
);
}
})}
</div>
) : null}
</div>
);
Issue is, filter will not return the custom element/value, it will always return the array element for which you return true from filter body.
Solution is, use only map or combination of filter and map.
Using map:
{
products.map((product, key) => product.checked ?
<RequestedProduct key={key} title={product.title} />
: null
}
Using combination of filter and map:
{
products
.filter(product => product.checked)
.map((product, key) => <RequestedProduct key={key} title={product.title}/>)
}
Check this snippet, you will get a better idea:
const arr = [
{a: 1},
{a: 2},
{a: 3},
{a: 4}
];
const afterFilter = arr.filter((el,i) => {
if(i%2) {
return `Hello world ${i}`;
}
});
// it will print the array items, not the Hello World string
console.log('afterFilter', afterFilter);
I'd recomment splitting the code a bit, which makes it intent a lot clearer. You'll end up with the following (for example), which should not be triggering errors.
The main problem is in the unintended side effects of the filter, whereas you most likely want to use a filter and a map. That makes the intent to another developer much clearer.
const contents = (products, getCurrentTime) => (
const filtered = products.filter(product => product.checked);
<div className="requested-tab-list-requested">
<div className="requested-tab-list-requested-time">
{getCurrentTime()}
</div>
{filtered.map((product, key) => <RequestedProduct key={key} title={product.title}/>)}
</div>
);
const Requested = ({products, getCurrentTime}) => {
const isAnythingChecked = products.some(product => product.checked);
return <div className="pepper-pin-body-tab requested-tab">
<div className="pepper-pin-body-tab-title">
Запрошенные
</div>
<div className="pepper-pin-body-tab-indicator"/>
{isAnythingChecked ? contents(products, getCurrentTime) : null}
</div>
};

How to return data in a react .map statement?

I want to use warningItem within my return statement in order to map some data into a react component.
I want to loop over area but have problems with syntax.
createWarnings = warningsRawData => {
return warningsRawData.map(warningItem => {
return (
<div>
<p className={styles.warningMainText} />
<p>warningItem.area[0]</p>
</div>
);
});
};
It looks like you are missing the brackets around it. Try:
createWarnings = warningsRawData => {
return warningsRawData.map( (warningItem, i) => {
return (
<div key={i}>
<p className={styles.warningMainText} />
<p>{warningItem.area[0]}</p>
</div>
);
});
};
Whenever you loop to return elememnt in react, add key attribute is must. Else you will get warning.And add {warningItem.area[0]}
createWarnings = warningsRawData => {
let values = warningsRawData.map((warningItem,index) => {
return (
<div key={index}>
<p className={styles.warningMainText} />
<p>{warningItem.area[0]}</p>
</div>
);
});
return values
}
;

Categories

Resources