How to get Name on chip or Index of chip? - javascript

1) I am using following method to create multiple chips (Material Design). In React
<div style={styles.wrapper} className="container">
{
arrayName.map((row, index)=>(
<Chip
style={styles.chip}
key={index}
onTouchTap={handleTouchTap}
>
{row.name}
</Chip>
))
}
</div>
I am not able to get value from event handler by using "event.target.value"
is there another way to get value on chips?
arrayName contains name of programming languages like Angular, React etc.
2) can change color of chips based on index I set?

You can bind the index or value directly to onTouchTap function, and access the value directly.
Binding Name:
<div style={styles.wrapper} className="container">
{
arrayName.map((row, index)=>(
<Chip
style={styles.chip}
key={index}
onTouchTap={this.handleTouchTap.bind(this, row.name)}
>
{row.name}
</Chip>
))
}
</div>
handleTouchTap(name){
console.log('name:', name);
}
Binding Index:
<div style={styles.wrapper} className="container">
{
arrayName.map((row, index)=>(
<Chip
style={styles.chip}
key={index}
onTouchTap={this.handleTouchTap.bind(this, index)}
>
{row.name}
</Chip>
))
}
</div>
handleTouchTap(index){
console.log('name:', arrayName[index].name);
}
Update:
To assign different colors to chip, First define the color codes in an To array like this:
let colors = ['#color1', '#color2', '#color3', '#color4'....];
Then Use Math.floor(Math.random() * colors.length); to pick a random no in the range of 0 to colors.length, assign that color to chip like this:
style={{backgroundColor: colors[Math.floor(Math.random() * colors.length)]}}
It will work.

Related

div's background is different than it's content (same values passed)

Ok, so I have a very strange problem (I'm using next.js).
I'm mapping shuffled array.
const otherPoepleData = shuffle(allPeople).filter(item => item.full_slug !== data.full_slug).slice(0, 3)
{otherPoepleData.map((item, index) =>
<SpeakerNew data={item} key={item.id} index={index} />
)}
To sum up the problem I've put inside SpeakerNew component following code:
<div style={{ backgroundImage: `url(${image.filename})` }}>
{image.filename}
</div>
And here are the results:
<div style="background-image:
url(https://something.com/blablaba57674676343zzx.png);">
https://something.com/blablaba13123123dasdzz.png
</div>
The content of the div is 100% correct, however the backgroundImage url is incorrect. Taken from completely other person from array I'm mapping. What coulde be the problem here?

Access Individual Elements in an Array from an API (react)

I am a beginner and I am trying to create a recipe app. I managed to set up an API that gives an Array of 10 objects each time I search for a meal like so.
I access the elements of each recipe using a map
{recipes.map(recipe =>(
<RecipeCard
key={recipe.recipe.label}
title ={recipe.recipe.label}
calories={recipe.recipe.calories}
image={recipe.recipe.image}
ingredients={recipe.recipe.ingredients}
/>
))}
Here is also my Const Recipe Card just for some more context. It functions fine.
const RecipeCard = ({title, calories, image, ingredients}) => {
const round = Math.round(calories);
return(
<div className = {style.recipe}>
<h1 >{title}</h1>
<ol className = {style.list}>
{ingredients.map(ingredient => (
<li>{ingredient.text}</li>
))}
</ol>
<p>calories: {round} </p>
<img className = {style.image} src={image} alt=""/>
<button>Add to Favorites</button>
</div>
)
}
I currently only want to access the information from the first array, but whenever I change recipes.map to recipes[0] it says that function does not exist. How should I go about accessing individual elements from the arrays provided from the API?
You can use .slice(0, 1) to create a shallow copy (a new array with just first element):
{recipes.slice(0, 1).map(recipe =>(
<RecipeCard
key={recipe.recipe.label}
title ={recipe.recipe.label}
calories={recipe.recipe.calories}
image={recipe.recipe.image}
ingredients={recipe.recipe.ingredients}
/>
))}
Or use destructuring:
const [recipe] = recipes // before "return"
// ....
<RecipeCard
key={recipe.recipe.label}
title ={recipe.recipe.label}
calories={recipe.recipe.calories}
image={recipe.recipe.image}
ingredients={recipe.recipe.ingredients}
/>
Or use index:
<RecipeCard
key={recipes[0]?.recipe.label}
title ={recipes[0]?.recipe.label}
calories={recipes[0]?.recipe.calories}
image={recipes[0]?.recipe.image}
ingredients={recipes[0]?.recipe.ingredients}
/>
The ?. is called optional chaining, you can use it to avoid error like Can't Read property of undefined, i.e. when the first element is undefined and you try to read its properties.

Multiple tags in list.map() syntax for React

I have the following code:
return (
</React.Fragment>
...
<div className="col-md-6">
{firstHalfy1.map(month => (<Field key={month.id} {...month}/>))}
</div>
</React.Fragment>
);
I want to add another tag/functional component after the component, but the syntax doesn't seem to work. Ideally I want something like:
{firstHalfy1.map(month => (<Field/><Component2/>))}
is this syntax possible as I am trying to render a button (Component2) after every input (Field)?
Thanks!
{firstHalfy1.map(month => (<div key={your key}><Field/><Component2/></div>))}
You need a wrapper for those components, such as a div or React.Fragment. Plus you need a key for each month.
You can use from fragment like this:
<>...
This empty tag is also fragment
{firstHalfy1.map(month => (
<React.Fragment key={month.id}>
<Field {...month}/>
<Component2/>
</React.Fragment>
))}

React.js acessing component props via e.target

i want to access items desc's to add them to 'cart'.
exactly i would like to change hook value on Item click.
thanks for your time
some code here:
{items.map(
item =>(
<Item src={item.recipe.image}
desc = {item.recipe.label}
price = {`${(item.recipe.label).length}$`}
/>
)
)}
You could pass the value in desc as an argument to the onClick function rather than trying to hack the value of an attribute/prop
{items.map(
item =>(
<Item src={item.recipe.image}
desc = {item.recipe.label}
price = {`${(item.recipe.label).length}$`}
onClick = {(e) => handleClick(e,item.recipe.label)}
/>
)
)}
and on the handleClick function get the second argument as the desc

Warning: flattenChildren(...): Encountered two children with the same key in reactjs

I'm using Tabs from Material UI where I'm displaying a List component filtered by the tab, please see the code of the Tabs in my Container Component:
<Tabs
className="DrawerTabs"
inkBarStyle={{ display: 'none' }}
>
<Tab label="Headline"
data-route="/headline"
onActive={this.handleActive}
className={this.isActive('Headline')}
>
<div>
<ModulesListContainer
filter="Headline"
/>
</div>
</Tab>
<Tab label="Body"
data-route="/body"
onActive={this.handleActive}
className={this.isActive('Body')}
>
<div>
<ModulesListContainer
filter="Body"
/>
</div>
</Tab>
<Tab
label="Other"
data-route="/other"
onActive={this.handleActive}
className={this.isActive('Other')}
>
<div>
<ModulesListContainer
filter="Other"
/>
</div>
</Tab>
</Tabs>
and the code of the ModuleList I placed in each of the tabs which is showing only items based on the filter passed from the Container Component:
const ModulesList = (props) => {
let ListItems = props.modulesProps.map(module => {
if (props.filter === module.category) {
return (
<ListItem
key={module.id}
className="ModulePreview"
>
{module.id} - {module.name} - {module.thumbnail}
<FontAwesome
name="plus-circle"
size="2x"
onClick={props.addModule.bind(this, module)}
className="AddModule"
/>
</ListItem>
)
}
})
return (
<div className="ModulesList">
<List>
{ListItems}
</List>
</div>
)
}
Even though I can see only the filtered items in each of the tabs (thus key is unique as each item is there only once) I'm still getting this warning:
Warning: flattenChildren(...): Encountered two children with the same
key, 1. Child keys must be unique; when two children share a key,
only the first child will be used.
Why is that?
Any help / ideas / tips would be highly appreciated.
Thanks a lot in advance! :)
Meaning of that line is module.id is not unique, there will be 2 objects in array that have the same id=1, to avoid that you can use index of object, it will always be unique.
Use this:
let ListItemsUI = [];
props.modulesProps.forEach((module, i) => {
if (props.filter === module.category) {
ListItemsUI.push (
<ListItem
key={i}
className="ModulePreview"
>
{module.id} - {module.name} - {module.thumbnail}
<FontAwesome
name="plus-circle"
size="2x"
onClick={props.addModule.bind(this, module)}
className="AddModule"
/>
</ListItem>
)
}
})
return (
<div className="ModulesList">
<List>
{ListItemsUI}
</List>
</div>
)
One more thing map is not suitable for these cases where you want to return only few element on the basis of condition, use forEach for that. Reason is if you don't return anything, by default map will return undefined.
Check the output of this example:
let a = [1,2,3,4,5,6,7,8];
let b = a.map(el=>{
if(el % 2 == 0)
return el;
})
console.log(b);

Categories

Resources