why nested map showing repeated content in react - reactjs

import "./styles.css";
const data = [
{
firstname: "junaid",
lastname: "hossain",
phones: [{ home: "015000" }, { office: "0177" }]
},
{
firstname: "arman",
lastname: "hossain",
phones: [{ home: "013000" }, { office: "0187" }]
}
];
export default function App() {
return (
<div className="App">
<div className="users">
{data.map((user, index) => {
const { firstname, lastname } = user;
return (
<div key={index} className="user">
<p>
name: {firstname} {lastname}
</p>
{user.phones.map((phone, i) => (
<div>
<p>home phone:{phone.home}</p>
<p>office phone:{phone.office}</p>
</div>
))}
</div>
);
})}
</div>
</div>
);
}
why a nested map showing repeated content? In this code, I don't want to show the empty office phone and home phone that I indicate in the picture by the red line. Now, what can I do to remove the extra content?
I would be very helpful if you tell me the answer.

Only show a <p> if the value you're interpolating later exists.
<div>
{phone.home && <p>home phone:{phone.home}</p>}
{phone.office && <p>office phone:{phone.office}</p>}
</div>

Solution-
<div className="users">
{data.map((user, index) => {
const { firstname, lastname } = user;
return (
<div key={index} className="user">
<p>
name: {firstname} {lastname}
</p>
{user.phones.map((phone, i) => (
<div>
{ !!phone?.home && <p>home phone:{phone.home}</p> }
{ !!phone?.office && <p>office phone:{phone.office}</p> }
</div>
))}
</div>
);
})}
</div>
Explanation-
{ user.phones.map((phone, i) => (
<div>
<p>home phone:{phone.home}</p>
<p>office phone:{phone.office}</p>
</div>
))}
In this loop, you are looping through 'user.phones', and for the first(or each) object in data variable, that is equals to (for the first one)->
[{ home: "015000" }, { office: "0177" }] //length = 2
So logically, that map will run two times.
For first time = { home: "015000" }, it will print,
<p>home phone:015000</p>
<p>office phone:undefined</p> // because in the first object, "office" key is not there
For second time = { office: "0177" },
<p>home phone:undefined</p> // because in the second object, "home" key is not there
<p>office phone:0177</p>

Related

React .map and setState weird behavior

The following is a simplified version of the part of the entire code.
The entire app is basically supposed to be a note taking app built on React, and currently I'm stuck on its respective note's editing function.
So the following script part basically is supported to do:
Render an array of <Card /> components based on the App this.state.notes array
By clicking the Edit note button it sets the App this.state.noteEditingId state
(so the React instance can know later which generated Card is currnetly being edited by the id)
By clicking the Save Edit button it tries to update the App this.state.notes array with the submitted edit text.
(see, I used a lot of filters to try to achieve this, since I don't have a good idea to how to more nicely achieve this. I believe there should be a nicer way)
But the result is not what I expect.
(While it supposed to achieve updating the expected Card component's notes array with the new note instance's new note "note" text,
it updates the notes array with the different notes's note instance's "note" text. I cannot explain this clearly, since this is an idk-what-is-wrong type of issue to me. )
const Card = (props) => {
const [noteEditing, setNoteEditing] = useState(false);
return (
<div {...props}>
<div>
<div>
<span>
<button onClick={() => {
noteEditing ? setNoteEditing(false) : setNoteEditing(true);
props.thisApp.setState({ noteEditingId: props.config.id })
}}>Edit note</button>
</span>
{noteEditing
?
<div>
<textarea className='__text' />
<button onClick={() => {
let note = document.querySelector('.__text').value
let current_note = props.thisApp.state.notes.filter(a => a.id == props.config.id)[0]
let notesAfterRemoved = props.thisApp.state.notes.filter(a => a.id !== props.config.id)
if (props.thisApp.state.noteEditingId == props.config.id)
{
props.thisApp.setState({
notes: [...notesAfterRemoved, { ...current_note, note: note }]
})
}
}}>
Save Edit
</button>
</div>
: ""
}
</div>
</div>
</div>
)
}
class App extends React.Component {
constructor() {
super();
this.state = {
notes: [
{
note: "note1.",
id: nanoid(),
},
{
note: "note2.",
id: nanoid(),
},
{
note: "note3.",
id: nanoid(),
},
]
};
}
render() {
return (
<div>
<h2>
Notes ({this.state.notes.length})
</h2>
<div className='__main_cards'>
<div>
{this.state.notes.map((a, i) => {
return <Card key={i} className="__card" thisApp={this} config={
{
note: a.note,
}
} />
})}
</div>
</div>
</div>
)
}
}
So what can I do fix to make the part work properly? Thanks.
You should pass the current note also and get rid of the filter in card component:
this.state.notes.map((note, i) => {
return (
<Card
key={i}
className="__card"
thisApp={this}
currentNote={note}
/>
);
})
And then remove this:
let current_note = props.thisApp.state.notes.filter(a => a.id == props.config.id)[0]
And then rather than finding the notes without the edited note you can create a new array with edited data like this:
const x = props.thisApp.state.notes.map((n) => {
if (n.id === props.currentNote.id) {
return {...n, note}
}
return n
})
And get rid off this line:
let notesAfterRemoved = props.thisApp.state.notes.filter(a => a.id !== props.config.id)
Also, change this
noteEditing ? setNoteEditing(false) : setNoteEditing(true);
To:
setNoteEditing(prev => !prev)
As it is much cleaner way to toggle the value.
And I believe, there is no need to check that if the noteEditingId is equal to current active note id.
So you can get rid off that also (Correct me if I am wrong!)
Here's the full code:
const Card = (props) => {
const [noteEditing, setNoteEditing] = useState(false);
const textareaRef = useRef();
return (
<div {...props}>
<div>
<div>
<span>
<button
onClick={() => {
setNoteEditing((prev) => !prev); // Cleaner way to toggle
}}
>
Edit note
</button>
</span>
{noteEditing && (
<div>
<textarea className="__text" ref={textareaRef} />
<button
onClick={() => {
let note = textareaRef.current.value;
const x = props.thisApp.state.notes.map(
(n) => {
if (n.id === props.currentNote.id) {
return { ...n, note };
}
return n;
}
);
props.thisApp.setState({
notes: x,
});
}}
>
Save Edit
</button>
</div>
)}
</div>
</div>
</div>
);
};
class App extends React.Component {
constructor() {
super();
this.state = {
notes: [
{
note: "note1.",
id: nanoid(),
},
{
note: "note2.",
id: nanoid(),
},
{
note: "note3.",
id: nanoid(),
},
],
};
}
render() {
return (
<div>
<h2>Notes ({this.state.notes.length})</h2>
<div className="__main_cards">
<div>
{this.state.notes.map((note, i) => {
return (
<Card
key={i}
className="__card"
thisApp={this}
currentNote={note}
/>
);
})}
</div>
</div>
</div>
);
}
}
}
);
props.thisApp.setState({
notes: x,
});
}
}}
>
Save Edit
</button>
</div>
)}
</div>
</div>
</div>
);
};
class App extends React.Component {
constructor() {
super();
this.state = {
notes: [
{
note: "note1.",
id: nanoid(),
},
{
note: "note2.",
id: nanoid(),
},
{
note: "note3.",
id: nanoid(),
},
],
};
}
render() {
return (
<div>
<h2>Notes ({this.state.notes.length})</h2>
<div className="__main_cards">
<div>
{this.state.notes.map((note, i) => {
return (
<Card
key={i}
className="__card"
thisApp={this}
currentNote={note}
/>
);
})}
</div>
</div>
</div>
);
}
}
I hope this is helpful for you!

Repeater with react

I am new to this and learning react at the moment. So i made a custom gutenberg block with 2 repeater fields. 1 is for a name and the second is for a number.
Technically it works. The fields are repeating etc. But the output i want to realize isn't working or i dont get it.
So in the html i want that this block repeat it self but i dont know how.
If i repeat it once, it works like a charm. When i want to repeat it dubble or more, the output gets under the older output:
1 Field
<div class="skills__skills" >
<div class="skills__skill">
<p>{ skillnameFields }</p>
<div class="container__bgcolor">
<div class="skills html progress__skill" style={{width:{ percentFields } }}>
<span>{ percentFields }</span>
</div>
</div>
</div>
</div>
When i want 2 fields this happends:
<div class="skills__skills" >
<div class="skills__skill">
<p>{ skillnameFields }</p>
<p>{ skillnameFields }</p>
<div class="container__bgcolor">
<div class="skills html progress__skill" style={{width:{ percentFields } }}>
<span>{ percentFields }</span>
<span>{ percentFields }</span>
</div>
</div>
</div>
</div>
How can i make it work that this happends:
<div class="skills__skills" >
<div class="skills__skill">
<p>{ skillnameFields }</p>
<div class="container__bgcolor">
<div class="skills html progress__skill" style={{width:{ percentFields } }}>
<span>{ percentFields }</span>
</div>
</div>
</div>
</div>
<div class="skills__skills" >
<div class="skills__skill">
<p>{ skillnameFields }</p>
<div class="container__bgcolor">
<div class="skills html progress__skill" style={{width:{ percentFields } }}>
<span>{ percentFields }</span>
</div>
</div>
</div>
</div>
Here is mine full code:
I hope some on can help me :)
/**
* BLOCK: project-drie
*
* Registering a basic block with Gutenberg.
* Simple block, renders and saves the same content without any interactivity.
*/
// Import CSS.
import './editor.scss';
import './style.scss';
// import components
import { useBlockProps, RichText, InnerBlocks, MediaUpload, InspectorControls, } from '#wordpress/block-editor';
const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
const { Button, IconButton, PanelBody, TextareaControl, TextControl } = wp.components;
const { Fragment } = wp.element;
/**
* Register: aa Gutenberg Block.
*
* Registers a new block provided a unique name and an object defining its
* behavior. Once registered, the block is made editor as an option to any
* editor interface where blocks are implemented.
*
* #link https://wordpress.org/gutenberg/handbook/block-api/
* #param {string} name Block name.
* #param {Object} settings Block settings.
* #return {?WPBlock} The block, if it has been successfully
* registered; otherwise `undefined`.
*/
registerBlockType( 'cgb/block-project-drie-skillbar', {
title: __( 'project-drie - Skill bar' ), // Block title.
icon: 'shield',
category: 'project drie',
supports: {
align: true,
},
keywords: [
__( 'project-drie — CGB skillbar' ),
__( 'skillbar' ),
__( 'skill-bar' ),
],
attributes: {
title: {
type: 'string',
source: 'text',
selector: 'figcaption',
},
subtitle: {
type: 'string',
source: 'text',
selector: '.my-content',
},
mediaID: {
type: 'number',
},
mediaURL: {
type: 'string',
source: 'attribute',
selector: 'img',
attribute: 'src',
},
skillname: {
type: 'array',
default: [],
},
percent: {
type: 'array',
default: [],
},
},
/**
* The edit function describes the structure of your block in the context of the editor.
* This represents what the editor will render when the block is used.
*
* The "edit" property must be a valid function.
*
* #link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
*
* #param {Object} props Props.
* #returns {Mixed} JSX Component.
*/
edit: props => {
const { attributes: {title, subtitle, mediaID, mediaURL }, className, setAttributes } = props;
const onChangeTitle = title => { setAttributes ( { title } ) };
const onChangeSubtitle = subtitle => { setAttributes ( { subtitle } ) };
const onSelectImage = ( media ) => { setAttributes( { mediaURL: media.url, mediaID: media.id,} );};
const handleAddSkillname = () => {
const skillname = [ ...props.attributes.skillname ];
skillname.push( {
skill: '',
} );
props.setAttributes( { skillname } );
};
const handleAddPercent = () => {
const percent = [ ...props.attributes.percent ];
percent.push( {
percentage: '',
} );
props.setAttributes( { percent } );
};
const handleRemoveSkillname = ( index ) => {
const skillname = [ ...props.attributes.skillname ];
skillname.splice( index, 1 );
props.setAttributes( { skillname } );
};
const handleRemovePercent = ( index ) => {
const percent = [ ...props.attributes.percent ];
percent.splice( index, 1 );
props.setAttributes( { percent } );
};
const handleSkillnameChange = ( skill, index ) => {
const skillname = [ ...props.attributes.skillname ];
skillname[ index ].skill = skill;
props.setAttributes( { skillname } );
};
const handlePercentChange = ( percentage, index ) => {
const percent = [ ...props.attributes.percent ];
percent[ index ].percentage = percentage;
props.setAttributes( { percent } );
};
let skillnameFields,
skillnameDisplay;
let percentFields,
percentDisplay;
if ( props.attributes.skillname.length ) {
skillnameFields = props.attributes.skillname.map( ( skillname, index ) => {
return <Fragment key={ index }>
<TextControl
className="skillbar__react__name"
placeholder="Add Skill Name. Example: HTML"
value={ props.attributes.skillname[ index ].skill }
onChange={ ( skill ) => handleSkillnameChange( skill, index ) }
/>
<IconButton
className="skillbar__remove__react__name"
icon="no-alt"
label="Delete location"
onClick={ () => handleRemoveSkillname( index ) }
/>
</Fragment>;
} );
percentFields = props.attributes.percent.map( ( percent, index ) => {
return <Fragment key={ index }>
<TextControl
className="skillbar__react__percent"
placeholder="Add Percent Skill. Example: 50%"
value={ props.attributes.percent[ index ].percentage }
onChange={ ( percentage ) => handlePercentChange( percentage, index ) }
/>
<IconButton
className="skillbar__remove__react__percent"
icon="no-alt"
label="Delete location"
onClick={ () => handleRemovePercent( index ) }
/>
</Fragment>;
} );
skillnameDisplay = props.attributes.skillname.map( ( skillname, index ) => {
return <p key={ index }>{ skillname.skill }</p>;
} );
percentDisplay = props.attributes.percent.map( ( percent, index ) => {
return <p key={ index }>{ percent.percentage }</p>;
} );
}
return [
<div className={ className }>
<InspectorControls key="1">
<PanelBody title={ __( 'Skill Name' ) }>
{ skillnameFields }
<Button
isDefault
onClick={ handleAddSkillname.bind( this ) }
>
{ __( 'Add Name' ) }
</Button>
</PanelBody>
<PanelBody title={ __( 'Percent' ) }>
{ percentFields }
<Button
isDefault
onClick={ handleAddPercent.bind( this ) }
>
{ __( 'Add percent' ) }
</Button>
</PanelBody>
</InspectorControls>
<div key="2" className={ props.className }>
<div className="wp-block-cgb-block-project-drie-skillbar-repeater">
<div className="wp-block-cgb-block-project-drie-skillbar-repeater-title">
<p> Press on Skill bar</p>
<h2>Skill Bar</h2>
</div>
<div className="wp-block-cgb-block-project-drie-skillbar-skillname">
<h3>Skill Name</h3>{ skillnameDisplay }
</div>
<div className="wp-block-cgb-block-project-drie-skillbar-percentage">
<h3>percentage</h3>{ percentDisplay }
</div>
</div>
</div>
<div className="wp-block-cgb-block-project-drie-skillbar-info">
<div className="wp-block-cgb-block-project-drie-skillbar-title">
<h2>{ __('Title', 'cgb')}</h2>
<RichText
tagName="div"
className="wp-block-cgb-block-project-drie-skillbar-titles"
placeholder={ __('Add your title here', 'cgb')}
onChange={ onChangeTitle}
value={ title }
/>
</div>
<div className="wp-block-cgb-block-project-drie-skillbar-subtext">
<h2>{ __('Sub-Text', 'cgb')}</h2>
<RichText
tagName="p"
className="wp-block-cgb-block-project-drie-skillbar-subtexts"
value={ subtitle }
onChange={ onChangeSubtitle }
placeholder={ __('Add your sub-text here', 'cgb')}
/>
</div>
</div>
<div className="wp-block-cgb-block-project-drie-skillbar-bgimages">
<h2>Right Side Image</h2>
<div className="wp-block-cgb-block-project-drie-skillbar-bgimage">
<MediaUpload
onSelect={ onSelectImage }
allowedTypes="image"
value={ mediaID }
render={ ( { open } ) => (
<Button className={ mediaID ? 'image-button' : 'button button-large' } onClick={ open }>
{ ! mediaID ? __( 'Upload Image', 'gutenberg-examples' ) : <img src={ mediaURL } alt={ __( 'Upload Recipe Image', 'gutenberg-examples' ) } /> }
</Button>
) }
/>
</div>
</div>
</div>
];
},
/**
* The save function defines the way in which the different attributes should be combined
* into the final markup, which is then serialized by Gutenberg into post_content.
*
* The "save" property must be specified and must be a valid function.
*
* #link https://wordpress.org/gutenberg/handbook/block-api/block-edit-save/
*
* #param {Object} props Props.
* #returns {Mixed} JSX Frontend HTML.
*/
save: ( props ) => {
const {attributes: { title } } = props;
const {attributes: { subtitle } } = props;
const {attributes: { mediaURL} } = props;
const skillnameFields = props.attributes.skillname.map( ( skillname, index ) => {
return <p key={ index }>{ skillname.skill }</p>;
} );
const percentFields = props.attributes.percent.map( ( percent, index ) => {
return <p key={ index }>{ percent.percentage }</p>;
} );
return (
<section class="skills_bar">
<div class="container skills__container">
<div class="row skills__row">
<div class="skills__content">
<div class="skills__info col-md-6">
<div class="skills__text">
<div class="skills__title">
<h2>{ title } </h2>
</div>
<div class="skills__subtext">
<p>{ subtitle }</p>
</div>
</div>
<div class="skills__skills" >
<div class="skills__skill">
<p>{ skillnameFields }</p>
<div class="container__bgcolor">
<div class="skills html progress__skill" style={{width:{ percentFields } }}>
<span>{ percentFields }</span>
</div>
</div>
</div>
</div>
</div>
<div class="skills__images col-md-6">
<div class="skills__image">
<img src={ mediaURL}/>
</div>
</div>
</div>
</div>
</div>
</section>
);
},
} );
It depends on your specific data model, but one solution would be to combine your skillname and percent attributes into a single skills attribute. That would be an array of objects. Then for your output you simply loop over the skills array and output the object pieces. In your edit function, when you add a new skill, just push the object into the skills array (e.g. setAttributes({skills: [...skills, {name: 'Skill name', percent: 50}]})).
attributes: {
skills: {
type: 'array',
default: [],
},
}
save: ({attributes}) => {
return skills.map((skill) => (
<div className="skills__skills" key={ skill.name }>
<div className="skills__skill">
<p>{ skill.name }</p>
<div className="container__bgcolor">
<div className="skills html progress__skill">
<span>{ skill.percent }</span>
</div>
</div>
</div>
</div>
));
}
Also, you'll want to use className instead of class or React will give you an error since class is a reserved word in JS. See this issue for more info.

Function invoking only for first item React

i wrote code to expand "more info" block after clicking button, but function invoking only for first item.
Is it happening beacuse i use let more = document.getElementById("more"); ?
How can i change code for expanding only specifed item?
const Currency = ({ filteredItems, isLoading }) => {
const addListeners = () => {
let more = document.querySelectorAll(".more-info");
more.forEach(item => {
item.addEventListener("click", toggle)
})
console.log(more)
}
const toggle = () => {
let more = document.getElementById("more");
if (more.className === "more-info") {
more.className = "more-info-active";
} else {
more.className = "more-info";
}
}
return isLoading ? (<div className="loader">Loading...</div>) : (
<div items={filteredItems}>
{filteredItems.map((item) => (
<div key={item.id} className="item-wrapper">
<div className="item">
<h2>{item.name}</h2>
<img src={item.image} alt="crypto symbol"></img>
<h3>{item.symbol}</h3>
<p>{item.current_price} pln</p>
<button onLoad={addListeners} onClick={toggle} className="info-btn" id="item-btn" >➜</button>
</div>
<div id="more" className="more-info">
<div className="more-data">
<div className="info-text">
<p>high_24: {item.high_24h}</p>
<p>low_24: {item.low_24h}</p>
</div>
<div>
<p>price_change_24h: {item.price_change_24h}</p>
<p>price_change_percentage_24h: {item.price_change_percentage_24h}</p>
</div>
<div>
<Sparklines className="sparkline" height={60} margin={10} data={item.sparkline_in_7d.price}>
<SparklinesLine style={{fill:"none"}} color="#b777ff" />
</Sparklines>
</div>
</div>
</div>
</div>
))}
</div>
);
}
Dont use document.getElement... , this is a Real DOM but React uses Virtual DOM.
Instead create a state with an array and on onClick event pass item as an argument and store in state , you can store only id e.g.
Last step, check in JSX if state includes item.id , if true then expand
this is an example , keep in mind this is not the only solution. Just simple example.
import React, { useState } from "react";
const fakeData = [
{
id: "123123-dfsdfsd",
name: 'Title One',
description: "Description bla bla bla One"
},
{
id: "343434-dfsdfsd",
name: 'Title Two',
description: "Description bla bla bla Two"
},
{
id: "6767676-dfsdfsd",
name: 'Title Three',
description: "Description bla bla bla Three"
}
]
function App() {
const [tabs, setTabs] = useState([]);
function _onToggle(item) {
const isExist = tabs.includes(item.id)
if (isExist) {
setTabs(prevData => prevData.filter(pd => pd !== item.id))
} else {
setTabs(prevData => [item.id, ...prevData])
}
}
return (
<div className="app">
<div>
{
fakeData.map((item, i) => (
<div key={i}>
<h3 onClick={() => _onToggle(item)}>{item.name}</h3>
<p style={{ display: tabs.includes(item.id) ? 'block' : 'none' }}>
{ item.description }
</p>
</div>
))
}
</div>
</div>
);
}
export default App;

How to take a link from one array and assign it to another?

Friends, how to show the logo for the company from "arr1", the link to which is located in "arr2"? That is, to make the logo consistent with the company
import React from "react";
import "./styles.css";
export default function App() {
const arr1 = [
{
id: "random1",
companyName: "Apple"
},
{
id: "random2",
companyName: "Samsung"
}
];
const arr2 = [
{
id: "random1",
companyName: "Apple",
logoUrl: "img.com/url"
},
{
id: "random2",
companyName: "Samsung",
logoUrl: "img.com/url"
}
];
const blockCreate = () => {
return arr1.map(item => {
return (
<p>
<span>ID {item.id} - </span>
<br />
{item.companyName}
<span>
<br />
<img src="#" />
</span>
</p>
);
});
};
return (
<div className="App">
<div>{blockCreate()}</div>
</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
arr1 - Apple === arr2 - AppleLogo (logoUrl)
Now trying to do like this
https://codesandbox.io/s/kind-bush-zlyi6
companyDetails is your array so, do like this arr2.companyDetails.find()
Change this
const blockCreate = (arr1, arr2) => {
return arr1.company.map(item => {
const src = arr2.companyDetails.find(a => a.id === item.id).logoUrl;
return (
<p>
<span>ID {item.id} - </span>
<br />
{item.companyName}
<span>
<br />
<img src={src} alt="pic"/>
</span>
</p>
);
});
};
Something like this:
import React from "react";
import "./styles.css";
export default function App() {
const arr1 = {
company: [
{
id: "random1",
companyName: "Apple"
},
{
id: "random2",
companyName: "Samsung"
}
]
};
const arr2 = {
companyDetails: [
{
id: "random1",
companyName: "Apple",
logoUrl: "img.com/url"
},
{
id: "random2",
companyName: "Samsung",
logoUrl: "img.com/url"
}
]
};
const blockCreate = (arr1, arr2) => {
return arr1.company.map(item => {
const src = arr2.find(a => a.id === item.id).logoUrl;
return (
<p>
<span>ID {item.id} - </span>
<br />
{item.companyName}
<span>
<br />
<img src={src} />
</span>
</p>
);
});
};
return (
<div className="App">
<div>{blockCreate(arr1, arr2)}</div>
</div>
);
}
Note that I have passed arr1 and arr2 into the blockCreate function. This is better form than just having it access the variables on the higher scope since it makes your blockCreate function more modular, hence reusable.
As a react developer you should think about how this component can be re-usable meaning you can pass a single array of object and then have the component to always render the list of details.
The right way of doing this is to prepare the data before passing it to this component (can be handled in the backend or front-end depends on how you are getting this data). This is not the component's job to map through two different arrays and figure out the relation between those and render the list.
Here is an example in ECMAScript6:
// Prepare the final data
const hash = new Map();
arr1.company.concat(arr2.companyDetails).forEach(obj => {
hash.set(obj.id, Object.assign(hash.get(obj.id) || {}, obj));
});
const finalArray = Array.from(hash.values());
const blockCreate = (finalArray) => {
return arr3.map(item => {
return (
<p>
<span>ID {item.id} - </span>
<br />
{item.companyName}
<span>
<br />
<img src={item.logoUrl} alt="logo" />
</span>
</p>
);
});
};

Iterate Item Inside JSX React Native [duplicate]

could you please tell me how to render a list in react js.
I do like this
https://plnkr.co/edit/X9Ov5roJtTSk9YhqYUdp?p=preview
class First extends React.Component {
constructor (props){
super(props);
}
render() {
const data =[{"name":"test1"},{"name":"test2"}];
const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
return (
<div>
hello
</div>
);
}
}
You can do it in two ways:
First:
render() {
const data =[{"name":"test1"},{"name":"test2"}];
const listItems = data.map((d) => <li key={d.name}>{d.name}</li>);
return (
<div>
{listItems }
</div>
);
}
Second: Directly write the map function in the return
render() {
const data =[{"name":"test1"},{"name":"test2"}];
return (
<div>
{data.map(function(d, idx){
return (<li key={idx}>{d.name}</li>)
})}
</div>
);
}
https://facebook.github.io/react/docs/jsx-in-depth.html#javascript-expressions
You can pass any JavaScript expression as children, by enclosing it within {}. For example, these expressions are equivalent:
<MyComponent>foo</MyComponent>
<MyComponent>{'foo'}</MyComponent>
This is often useful for rendering a list of JSX expressions of arbitrary length. For example, this renders an HTML list:
function Item(props) {
return <li>{props.message}</li>;
}
function TodoList() {
const todos = ['finish doc', 'submit pr', 'nag dan to review'];
return (
<ul>
{todos.map((message) => <Item key={message} message={message} />)}
</ul>
);
}
class First extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [{name: 'bob'}, {name: 'chris'}],
};
}
render() {
return (
<ul>
{this.state.data.map(d => <li key={d.name}>{d.name}</li>)}
</ul>
);
}
}
ReactDOM.render(
<First />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Shubham's answer explains very well. This answer is addition to it as per to avoid some pitfalls and refactoring to a more readable syntax
Pitfall : There is common misconception in rendering array of objects especially if there is an update or delete action performed on data. Use case would be like deleting an item from table row. Sometimes when row which is expected to be deleted, does not get deleted and instead other row gets deleted.
To avoid this, use key prop in root element which is looped over in JSX tree of .map(). Also adding React's Fragment will avoid adding another element in between of ul and li when rendered via calling method.
state = {
userData: [
{ id: '1', name: 'Joe', user_type: 'Developer' },
{ id: '2', name: 'Hill', user_type: 'Designer' }
]
};
deleteUser = id => {
// delete operation to remove item
};
renderItems = () => {
const data = this.state.userData;
const mapRows = data.map((item, index) => (
<Fragment key={item.id}>
<li>
{/* Passing unique value to 'key' prop, eases process for virtual DOM to remove specific element and update HTML tree */}
<span>Name : {item.name}</span>
<span>User Type: {item.user_type}</span>
<button onClick={() => this.deleteUser(item.id)}>
Delete User
</button>
</li>
</Fragment>
));
return mapRows;
};
render() {
return <ul>{this.renderItems()}</ul>;
}
Important : Decision to use which value should we pass to key prop also matters as common way is to use index parameter provided by .map().
TLDR; But there's a drawback to it and avoid it as much as possible and use any unique id from data which is being iterated such as item.id. There's a good article on this - https://medium.com/#robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318
Try this below code in app.js file, easy to understand
function List({}) {
var nameList = [
{ id: "01", firstname: "Rahul", lastname: "Gulati" },
{ id: "02", firstname: "Ronak", lastname: "Gupta" },
{ id: "03", firstname: "Vaishali", lastname: "Kohli" },
{ id: "04", firstname: "Peter", lastname: "Sharma" }
];
const itemList = nameList.map((item) => (
<li>
{item.firstname} {item.lastname}
</li>
));
return (
<div>
<ol style={{ listStyleType: "none" }}>{itemList}</ol>
</div>
);
}
export default function App() {
return (
<div className="App">
<List />
</div>
);
}
import React from 'react';
class RentalHome extends React.Component{
constructor(){
super();
this.state = {
rentals:[{
_id: 1,
title: "Nice Shahghouse Biryani",
city: "Hyderabad",
category: "condo",
image: "http://via.placeholder.com/350x250",
numOfRooms: 4,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 43
},
{
_id: 2,
title: "Modern apartment in center",
city: "Bangalore",
category: "apartment",
image: "http://via.placeholder.com/350x250",
numOfRooms: 1,
shared: false,
description: "Very nice apartment in center of the city.",
dailyPrice: 11
},
{
_id: 3,
title: "Old house in nature",
city: "Patna",
category: "house",
image: "http://via.placeholder.com/350x250",
numOfRooms: 5,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 23
}]
}
}
render(){
const {rentals} = this.state;
return(
<div className="card-list">
<div className="container">
<h1 className="page-title">Your Home All Around the World</h1>
<div className="row">
{
rentals.map((rental)=>{
return(
<div key={rental._id} className="col-md-3">
<div className="card bwm-card">
<img
className="card-img-top"
src={rental.image}
alt={rental.title} />
<div className="card-body">
<h6 className="card-subtitle mb-0 text-muted">
{rental.shared} {rental.category} {rental.city}
</h6>
<h5 className="card-title big-font">
{rental.title}
</h5>
<p className="card-text">
${rental.dailyPrice} per Night · Free Cancelation
</p>
</div>
</div>
</div>
)
})
}
</div>
</div>
</div>
)
}
}
export default RentalHome;
Try this:
class First extends React.Component {
constructor (props){
super(props);
}
render() {
const data =[{"name":"test1"},{"name":"test2"}];
const listItems = data.map((d) => <li key={d.name}>{d.name}</li>;
return (
<div>
{listItems}
</div>
);
}
}

Resources