Function invoking only for first item React - reactjs

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;

Related

why nested map showing repeated content in react

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>

React vertical Nested List open and close sub List

i have a react.js component in which i am displaying states and under i am displaying districts. To display this list it's working fine. The problem i want when i press any sates only that particular state sublist should display not all states sublist.
import React,{useState} from "react"
Const [open,,setOpen]=useState(false);
//Wrapper component
</div>
{states.map((city, index) => {
return <StateList state={state} key={index} />;
})}
</div>
//state component
<div onClick={()=>setOpen(!open)}>
<span >{state.name}</span>
<svg
viewBox="0 0 24 24"
className={`
${open ? "rotate-180" : ""}
`}
>
</svg>
</h2>
{open && <AreaList area={city} />}
</div>
//district component
const AreaList = ({ state }) => {
return state.districts.map((district) => (
<li>
<span className="ml-2 text-outer-space">
{district.name}
</span>
</li>
));
};
Here is working solution (without styles):
Codesandbox
import { useState } from "react";
const data = [
{
name: "Fujairah",
districts: [
{ name: "Al Buthna" },
{ name: "Al Bedia" },
{ name: "Town Center" },
{ name: "Wadi Al Sedr" }
]
},
{
name: "Abu Dhabi",
districts: [{ name: "Al Aman" }, { name: "Al Bahya" }]
}
];
const App = () => {
return (
<div>
{data.map((city) => {
return <City key={city.name} city={city} />;
})}
</div>
);
};
const City = ({ city }) => {
const [open, setOpen] = useState(false);
return (
<div onClick={() => setOpen(!open)}>
<h2>
<span>{city.name}</span>
</h2>
{open && <DistrictList city={city} />}
</div>
);
};
const DistrictList = ({ city }) => {
return city.districts.map((district) => (
<li key={district.name}>
<span>{district.name}</span>
</li>
));
};
export default App;

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.

React, passing a function in props is not working

I am trying to delete a certain entry in my list according to its index. However, the delete button is in a separate component. So I need to pass the function that deletes the entry in the list from my current app component to the child content component.
The App.js is:
import { useState } from 'react';
import './App.css';
import Content from './components/Content/Content';
function App() {
const Tours = [
{
image: "",
title: "",
price: "$",
text: ""
}
]
const [list, setList] = useState(Tours);
function handleRemove(id) {
console.log(id)
const newList = list.filter((item) => item.id !== id);
setList(newList);
}
return (
<div>
{list.map((value, index) => {
return (
<div key={index}>
<Content tour={value} delete={ () => handleRemove(index)}/>
</div>)
})
}
</div>
);
}
export default App;
component.js is:
const Content = (props) => {
return (
<div className="single-tour">
<img src = {props.tour.image} alt= {props.tour.title}></img>
<div className="container">
<h4 className ="title">{props.tour.title}</h4>
<h4 className="tour-price">{props.tour.price}</h4>
<button className="delete-btn" onClick={()=> props.delete}>Delete</button>
</div>
</div>
);
};
export default Content;
the console.log in the handleDelete is not showing, meaning the function is not being passed. What is the problem?
Please try:
onClick={()=> props.delete()}
or
onClick={props.delete}
In order to remove the card according to the id values, please also add them to your Tours object:
const Tours = [
{
image: "",
title: "",
price: "$",
text: "",
id: 1,
}
]
You should pass the value to the function like this.
here is the codesandbox link
https://codesandbox.io/s/react-func-props-j6idr?file=/src/index.js
you should and id field to the the list of tours and pass it down to the component
function App() {
const Tours = [
{
id: 0,
image: "https://via.placeholder.com/150/92c952",
title: "title 1",
price: "$ 1",
text: "text"
},
{
id: 1,
image: "https://via.placeholder.com/150/d32776",
title: "title 2",
price: "$ 2",
text: "description"
}
];
const [list, setList] = useState(Tours);
function handleRemove(id) {
console.log(id);
const newList = list.filter((item) => item.id !== id);
setList(newList);
}
return (
<div>
{list.map((value, index) => {
return (
<div key={value.id}>
<Content tour={value} delete={() => handleRemove(index)} />
</div>
);
})}
</div>
);
}
in the content component, you should pass the id of the tour object to the function
const Content = (props) => {
return (
<div className="single-tour">
<img src={props.tour.image} alt={props.tour.title}></img>
<div className="container">
<h4 className="title">{props.tour.title}</h4>
<h4 className="tour-price">{props.tour.price}</h4>
<button
className="delete-btn"
onClick={() => props.delete(props.tour.id)}
>
Delete
</button>
</div>
</div>
);
};
You're filtering the array by id which the objects do not have. What you can do is pass an index the filter method:
const newList = list.filter((item, i) => i !== index);
However, a better practice would be to add an id attribute to the object instead of relying on order.

Need help for loop in React

I'm learning React, JS and I'm trying to use the .map method to display some data in an array. For each element in the array I create a button to show/hide a description with css and I'm looking for a way to only show the description of one element instead of all descriptions. It is probably unclear but here is the code :
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [showDescription, setshowDescription] = useState(false);
const [anArray] = useState([
{ title: "First Div", description: "First description"},
{ title: "Antoher Div", description: "Another description"}
]);
return (
<div className="App">
{anArray.map((val, index) => {
return (
<div className="div" key={index}>
<div className="title">{val.title}</div>
<button className="btn" onClick={() => setshowDescription(!showDescription)}>
Show description
</button>
<div id={showDescription ? "display" : "hidden"}>
<div className="description">{val.description}</div>
</div>
</div>
);
})}
</div>
);
}
Do you have any idea please ?
Issue
You've a single boolean showDescription state that is toggling every description.
Solution
Store an index of the description you want to toggle. Use the index to match the currently mapped element. Conditionally render the description
export default function App() {
const [showId, setShowId] = useState(null);
// curried function to toggle to new index or back to null to hide
const toggleDescription = id => () => setShowId(showId => showId === id ? null : id);
const [anArray] = useState([
{ title: "First Div", description: "First description"},
{ title: "Antoher Div", description: "Another description"}
]);
return (
<div className="App">
{anArray.map((val, index) => {
return (
<div className="div" key={index}>
<div className="title">{val.title}</div>
<button className="btn" onClick={toggleDescription(index)}> // <-- pass index
Show description
</button>
{showId === index && ( // <-- check for index match
<div>
<div className="description">{val.description}</div>
</div>
)}
</div>
);
})}
</div>
);
}
You can use index to show/hide your div. The issue is you are using only one Boolean value to handle it.
export default function App() {
const [showDescriptionIndex, setshowDescriptionIndex] = useState(-1);
const [anArray] = useState([
{ title: "First Div", description: "First description"},
{ title: "Antoher Div", description: "Another description"}
]);
return (
<div className="App">
{anArray.map((val, index) => {
return (
<div className="div" key={index}>
<div className="title">{val.title}</div>
<button className="btn" onClick={() => setshowDescriptionIndex(index)}>
Show description
</button>
<div id={showDescriptionIndex === index ? "display" : "hidden"}>
<div className="description">{val.description}</div>
</div>
</div>
);
})}
</div>
);
}
Try It
import "./styles.css";
import React, { useState } from "react";
export default function App() {
const [showDescription, setshowDescription] = useState({});
const [anArray] = useState([
{ title: "First Div", description: "First description"},
{ title: "Antoher Div", description: "Another description"}
]);
return (
<div className="App">
{anArray.map((val, index) => {
return (
<div className="div" key={index}>
<div className="title">{val.title}</div>
<button className="btn" onClick={() => setshowDescription({...showDescription, [index]: !showDescription[index]})}>
Show description
</button>
<div id={showDescription && showDescription[index] ? "display" : "hidden"}>
{showDescription[index]}
<div className="description">{val.description}</div>
</div>
</div>
);
})}
</div>
);
}
Tip: Use class="show/hide" instead of id="show/hide"

Resources