Mapping within a map in ReactJS - javascript

I'm trying to map each value and font awesome icon to each button.
Data for each value
const test = ["440", "756", "28", "249", "345", "397", "301", "507", "648"]
Code to map over font awesome icons
const icons = [
{ id:0, name: faHeadphonesAlt, label:'Music'},
{ id:1, name: faPhone, label:'Phone'},
{ id:2, name: faHeartbeat, label:'Health'},
{ id:3, name: faShoppingBag, label: 'Shopping'},
{ id:4, name: faShieldAlt, label: 'Security'}
]
Attempted resolution
test.map(a => {
return (
<div>
<button>
{
icons.map(icon => {
return(
<FontAwesomeIcon
id={icon.id}
icon={icon.name}
/>
)
})
}
<hr />
£{a}
</button>
</div>
)
}
)
Any ideas on how I can get each icon to show up in each button whilst mapping over the array of values?

Hi if you want to show one icon for each button ordered by index see this
https://codesandbox.io/s/serene-driscoll-03s2n
you don't need to map over each icon , also you have 9 buttons and 5 icons so i make them 9 icons
so your JSX component render should return
return test.map((a, indx) => {
return (
<div>
<button>
<FontAwesomeIcon id={icons[indx].id} icon={icons[indx].name} />
<hr />£{a}
</button>
</div>
);
});
Hope that help's😘

the return needs to come first:
return <div>
{test.map(a => (
<button>
{
icons.map(icon => {
return(
<FontAwesomeIcon
id={icon.id}
icon={icon.name}
/>
)
})
}
<hr />
£{a}
</button>
)}
</div>

Related

map function not showing elements on screen

i have this part of code the map function did not show any element of the array, if i console.log the variable it shows me the elements but for some reasons i can't show the elements on the screen.
Code
function Solution({list}){
const data = list
console.log(data);
return(
<div>
{
data?.map((item) => {
return (
<div>
<p> {item.title} </p>
</div>
)
})
}
</div>
)
}
export default Solution;
const list = [
{
title: "Home"
},
{
title: "Service",
subItem: ["Clean", "Cook"]
},
{
title: "Kitchen",
subItem: ["Wash", "Dish"]
},
];
Solution({list})
Please, just pass "list" link this.
<Solution list={list}/>
Hope will help you, Thanks)
Check this out
import React from 'react';
function Solution({list}){
const data = list
console.log(list);
return(
<div>
{
data?.map((item) => {
return (
<div key={item.id}>
<p> {item.title} </p>
</div>
)
})
}
</div>
)
}
export function App(props) {
const list = [
{
id:1,
title: "Home"
},
{
id:2,
title: "Service",
subItem: ["Clean", "Cook"]
},
{
id:3,
title: "Kitchen",
subItem: ["Wash", "Dish"]
},
];
return (
<div className='App'>
<Solution list={list} />
</div>
);
}
// Log to console
console.log('Hello console')
Have a unique key prop for each element when you map an array and send list array as props to your Solution component

How to get the "x" element in React JS while using the map object

I have an array with objects I am using map to render the elements on the page, The problem is that I want to get the last object from the array (in my case it is 'documents') and set a class for it to style it, you can also see my code in codesandbox
export default function Nav() {
const [navItems] = useState([
{
id: 1,
name: "Home",
link: "/dashboard"
},
{
id: 2,
name: "Investments",
link: "/investments"
},
{
id: 3,
name: "Organize",
link: "/organize"
},
{
id: 4,
name: "Documents",
link: "/documents"
}
]);
return (
<div className="App">
{navItems.map((i) => {
return (
<div key={i.id}>
<p>{i.name}</p>
</div>
);
})}
</div>
);
}
Check the index of the item while mapping through it. And check if the index is equal to the navItems.length - 1. Check this-
<div className="App">
{navItems.map((item, index) => {
return (
<div
key={item.id}
className={index === navItems.length - 1 ? 'your-desired-class': ''}>
<p>{item.name}</p>
</div>
);
})}
</div>

How to clear Multiselect Dropdown in Semantic UI React using a button?

I have a Semantic UI React Multiselect Dropdown inside a React functional component and want to have buttons inside the menu, as such (still need to center them...)
How can I clear the selected values using the 'Clear' button?
I am able to clear the selection using the 'x' icon, but that's built into the component.
<Dropdown
search
multiple
selection
clearable
closeOnSelectionChange={false}
options={filterInitialSuggestions()}
className='selectDropdown'
header={dropdownButtons()}
/>
const dropdownButtons = () => {
return (
<div>
<Button positive size='mini'>
Save
</Button>
<Button grey size='mini' onClick={() => console.log('I want to reset the multi select dropdown')}>
Clear
</Button>
<Divider />
</div>
);
};
'Save' and 'Clear' buttons with React useState(). In Reactjs you don't need to use DOM queryselector.
https://codesandbox.io/s/white-leftpad-q6re3?file=/src/Fun.jsx
import React, { Component } from 'react';
import { Dropdown } from 'semantic-ui-react';
const options = [
{ key: 1, text: 'Choice 1', value: 1 },
{ key: 2, text: 'Choice 2', value: 2 },
{ key: 3, text: 'Choice 3', value: 3 },
{ key: 4, text: 'Choice 4', value: 4 },
{ key: 5, text: 'Choice 5', value: 5 },
{ key: 6, text: 'Choice 6', value: 6 },
]
class Example extends Component {
state = {
dropval: []
}
onDropChange = (e, { value }) => {
this.setState(
(prevState) => { return { ...prevState, dropval: value } },
// () => console.log(this.state)
)
}
render() {
return (
<div>
<Dropdown
search
multiple
selection
clearable
closeOnSelectionChange={false}
options={options}
className='selectDropdown'
onChange={this.onDropChange}
value={this.state.dropval}
style={{ width: 300 }}
/>
</div>
);
}
}
export default Example;
I figured out how to solve this issue. I'm not sure if this is the best way, but it seems to work decently.
const dropdownButtons = () => {
return (
<>
<div className='dropdown-saveButton'>
<Button
positive
size='mini'
onClick={() => {
saveValues();
}}
>
Save
</Button>
<Button size='mini' onClick={clearDropdown}>
Clear
</Button>
</div>
<Divider inverted />
</>
);
};
const clearDropdown = e => {
var element = dropdownRef.current.querySelector('[aria-selected="true"]');
if (element) {
dropdownRef.current.querySelector('.clear')?.click();
}
};
<Dropdown
multiple
selection
fluid
clearable
header={dropdownButtons} />

React modal custom component not showing the correct data

I have built this modal component using react hooks. However the data that the modal shows when it pops up its incorrect (it always shows the name property for last element in the array).
//Modal.js
import ReactDOM from 'react-dom';
const Modal = ({ isShowing, hide, home_team }) => {return isShowing ? ReactDOM.createPortal(
<React.Fragment>
<div className="modal-overlay"/>
<div className="modal-wrapper">
<div className="modal">
<div className="modal-header">
<a>Home team: {home_team}</a>
<button type="button" className="modal-close-button" onClick={hide}>
</button>
</div>
</div>
</div>
</React.Fragment>, document.body
) : null;}
export default Modal;
// Main component
const League = ({ league, matches }) =>{
const {isShowing, toggle} = useModal();
return (
<Fragment>
<h2>{league}</h2>
{
matches.map((
{
match_id,
country_id,
home_team
}
) =>
{
return (
<div>
<p>{match_id}</p>
<button className="button-default" onClick={toggle}>Show Modal</button>
<a>{home_team}</a>
<Modal
isShowing={isShowing}
hide={toggle}
home_team={home_team}
/>
<p>{home_team}</p>
</div>
)
})
}
</Fragment>
)};
This is what matches data set looks like:
[{
match_id: "269568",
country_id:"22",
home_team: "Real Kings"
},
{
match_id: "269569",
country_id:"22",
home_team: "Steenberg United"
},
{
match_id: "269570",
country_id:"22",
home_team: "JDR Stars "
},
{
match_id: "269571",
country_id:"22",
home_team: "Pretoria U"
},
]
I am not sure whats going on because the data seems to be passed fine.
<p>{home_team}</p>
in the main component is showing everytime the expected property, however the Modal always shows the last home_team item in the array (e.g.Pretoria U)
you need to call useModal inside of the map function. otherwise you will open on toggle all Modals and the last one overlaps the others
const HomeTeam = ({ match_id, country_id, home_team }) => {
const {isShowing, toggle} = useModal();
return (
<div>
<p>{match_id}</p>
<button className="button-default" onClick={toggle}>Show Modal</button>
<a>{home_team}</a>
<Modal
isShowing={isShowing}
hide={toggle}
home_team={home_team}
/>
<p>{home_team}</p>
</div>
)
}
const League = ({ league, matches }) => (
<Fragment>
<h2>{league}</h2>
{ matches.map((match) => <Hometeam {...match} /> }
</Fragment>
);

Redux-form not formatting post data and [object Object] issue

I have two problems that are a result of each other. I populate two fields with initialValue data, I can then push another field to the array. The issue came about when I tried to amend the initialValue structure from:
initialValues: {
rockSingers: [ "Axl Rose", "Brian Johnson"]
}
to:
initialValues: {
rockSingers: [{ singer: "Axl Rose" }, { singer: "Brian Johnson" }]
}
The first problem is that the field now returns [object Object]. Upon submitting the form the correct json format is displayed until I come on to my 2nd issue... when adding a new value that does not format the same as the initialValue data - e.g.
{
"rockSingers": [
{
"singer": "Axl Rose"
},
{
"singer": "Brian Johnson"
},
"Tom Rudge"
]
}
Here is the codesandbox - https://codesandbox.io/s/8kzw0pw408
Modify renderRockSingers so that you are grabbing the object, not a string.
const renderRockSingers = ({ fields }) => (
<div>
<h3>Rock Singers:</h3>
{fields.map((rockSinger) => (
<div>
<Field name={`${rockSinger}.singer`} key="index" component="input" />
</div>
))}
<button type="button" onClick={() => fields.push()}>
Add more
</button>
</div>
);
More on the FieldArray component here: fieldarrays
Try this:
const renderRockSingers = ({ fields }) => (
<div>
<h3>Rock Singers:</h3>
{fields.map((rockSinger, index) => (
<div>
<Field
name={rockSinger}
format={value => value.singer}
parse={value => ({ singer: value })}
key={index}
component="input"
/>
</div>
))}
<button type="button" onClick={() => fields.push({ singer: '' })}>
Add more
</button>
</div>
);
<Field
name={rockSinger}
key={index}
component="input"
format={(value, name) => (value !== undefined ? value.singer : "")}
normalize={value => ({ singer: value })}
/>
Code Sandbox: https://codesandbox.io/s/7m1p9600y0

Categories

Resources