Repeater with react - reactjs

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.

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>

Cannot add item to cart when click on the button

When i click on the cart symbol, it changes its value to be in cart but actually my product is not rendered on the cart component, is there something wrong or missing in my code, please help me to fix it! Thank you so much!
Context.js:
class ProductProvider extends React.Component {
state = {
products: storeProducts,
detailProduct: detailProduct,
cart: [],
modalOpen: false,
modalProduct: detailProduct
};
getItem = (id) => {
const product = this.state.products.find((item) => item.id === id);
return product;
};
addToCart = (id) => {
console.log("add to cart");
let tempProducts = [...this.state.products];
const index = tempProducts.indexOf(this.getItem(id));
const product = tempProducts[index];
product.inCart = true;
product.count = 1;
const price = product.price;
product.total = price;
this.setState(() => {
return (
{ products: tempProducts, cart: [...this.state.cart, product] },
() => console.log(this.state)
);
});
};
openModal = (id) => {
const product = this.getItem(id);
this.setState(() => {
return { modalProduct: product, openModal: true };
});
};
closeModal = (id) => {
this.setState(() => {
return { modalOpen: false };
});
};
Cart.js:
import React from "react";
import CartColumns from "./CartColumns";
import CartList from "./CartList";
import EmptyCart from "./EmptyCart";
import { ProductContext } from "../App";
export default class Cart extends React.Component {
render() {
return (
<div>
<ProductContext.Consumer>
{(value) => {
console.log(value, "inside Product COnt");
if (value.length > 0) {
return (
<div>
<CartColumns />
<CartList items={items} />
</div>
);
} else {
<EmptyCart />;
}
}}
</ProductContext.Consumer>
</div>
);
}
}
CartList.js:
import React from "react";
import CartItem from "./CartItem";
export default function CartList(props) {
const { items } = props;
return (
<div>
{items.cart.map((item) => (
<CartItem
key={item.id}
item={item}
increment={item.increment}
decrement={item.decrement}
/>
))}
</div>
);
}
CartItem.js:
import React from "react";
function CartItem(props) {
const { id, title, img, price, total, count } = props.item;
const { increment, decrement, removeItem } = props;
return (
<div className="row my-1 text-capitalize text-center">
<div className="col-10 mx-auto col-lg-2">
<img
src={img}
style={{ width: "5rem", heigth: "5rem" }}
className="img-fluid"
alt=""
/>
</div>
<div className="col-10 mx-auto col-lg-2 ">
<span className="d-lg-none">product :</span> {title}
</div>
<div className="col-10 mx-auto col-lg-2 ">
<strong>
<span className="d-lg-none">price :</span> ${price}
</strong>
</div>
<div className="col-10 mx-auto col-lg-2 my-2 my-lg-0 ">
<div className="d-flex justify-content-center">
<div>
<span className="btn btn-black mx-1">-</span>
<span className="btn btn-black mx-1">{count}</span>
<span className="btn btn-black mx-1">+</span>
</div>
</div>
</div>
<div className="col-10 mx-auto col-lg-2 ">
<div className=" cart-icon">
<i className="fas fa-trash" />
</div>
</div>
<div className="col-10 mx-auto col-lg-2 ">
<strong>item total : ${total} </strong>
</div>
</div>
);
}
export default CartItem;
Sandbox link for better observation:https://codesandbox.io/s/cart-code-addict-forked-l6tfm?file=/src/cart/CartItem.js
There were few issues
Change following
this.setState(() => {
return (
{ products: tempProducts, cart: [...this.state.cart, product] },
() => console.log(this.state)
);
});
to
this.setState(
{
products: tempProducts,
cart: [...this.state.cart, product]
},
() => console.log(this.state)
);
And need to use value.cart to check for length and when passing as a prop.
Instead of
if (value.length > 0) {
return (
<div>
<CartColumns />
<CartList items={items} />
</div>
);
}
It should be
if (value.cart.length > 0) {
return (
<div>
<CartColumns />
<CartList items={value.cart} />
</div>
);
}
And in CartList,
Instead of
{
items.cart.map(item => (
<CartItem
key={item.id}
item={item}
increment={item.increment}
decrement={item.decrement}
/>
));
}
it should be
{
items.map(item => (
<CartItem
key={item.id}
item={item}
increment={item.increment}
decrement={item.decrement}
/>
));
}
Now it shows the cart with items
Code sandbox => https://codesandbox.io/s/cart-code-addict-forked-c3kug?file=/src/cart/CartList.js

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"

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;

Force update to make functional component re-render

I'm doing pokedex (pokemon wiki stuff). I want to change my component view, when clicking on pokemon images (description lookalike). When I click on an image - nothing happens (firstly, I want at least pokemon's name to be added to the pokemonDescription array). What am I doing wrong?
let pokemonDescription = [];
const useForceUpdate = () => {
const [value, setValue] = useState(true);
return () => setValue(value => !value);
}
const forceUpdate = useForceUpdate();
const onPokemonClick = (event) => {
console.log(
"wrapper clicked, event.target - ",
event.target.getAttribute('data-name')
);
pokemonDescription = [];
pokemonDescription.push(event.target.getAttribute('data-name'));
console.log("description array -", pokemonDescription);
forceUpdate();
};
useEffect(() => {
document.querySelector(".wrapper").addEventListener("click", onPokemonClick);
...
return () => {
document.querySelector(".wrapper").removeEventListener("click", onPokemonClick);
};
}, []);
...
return (
<div className="Pokemons">
<div className="column pokemons-list">
<div className="wrapper">
{
pokemonsData.map((p, id) => (
<div className="box" key={ id }>
<img
src={ p.sprites.front_default }
alt="pokemon-img"
title={ p.name }
className="icon"
data-name={p.name}
/>
{ p.name}
<div className="container">
{ pokemonsTypes[id] }
</div>
</div>
))
}
</div>
...
</div>
<div className="column description">
{ pokemonDescription }
</div>
</div>
)
You should add pokemonDescription to your component state
const [pokemonDescription, setPokemonDescription] = useState([]);
Remove the forceUpdate function and hook, it is unnecessary.
Attach the click handlers to the elements with the data-name attribute you are trying to handle.
Map the pokemonDescription state array to renderable JSX. I simply used a div, but you should use whatever your UI design requires.
const onPokemonClick = (event) => {
setPokemonDescription(names => [
...names,
event.target.getAttribute('data-name'),
]);
};
...
return (
<div className="Pokemons">
<div className="column pokemons-list">
<div className="wrapper">
{
pokemonsData.map((p, id) => (
<div className="box" key={ id }>
<img
src={ p.sprites.front_default }
alt="pokemon-img"
title={ p.name }
className="icon"
data-name={p.name}
onClick={onPokemonClick} // <-- attach click handler to img element
/>
{ p.name}
<div className="container">
{ pokemonsTypes[id] }
</div>
</div>
))
}
</div>
...
</div>
<div className="column description">
{pokemonDescription.map(name => (
<div>{name}</div>
))}
</div>
</div>
)
Add pokemonDescription to state instead of some local variable and it will solve your issue.
Try to avoid using forceUpdate, most of the times it means only that you are doing something silly.
I don't what that useForceUpdate does , but here is how would go about adding pokemon names to description array which is a state variable in my answer
const [pokemonDescription , setPokemonDescription ] = useState(null);
const onPokemonClick = (p) => {
const tempPokemonDescription = [...pokemonDescription ];
pokemonDescription.push(p.name);
console.log("description array -", pokemonDescription);
setPokemonDescription(tempPokemonDescription )
};
...
return (
<div className="Pokemons">
<div className="column pokemons-list">
<div className="wrapper">
{
pokemonsData.map((p, id) => (
<div className="box" onClick={e=>onPokemonClick(p)} key={ id }>
<img
src={ p.sprites.front_default }
alt="pokemon-img"
title={ p.name }
className="icon"
/>
{ p.name}
<div className="container">
{ pokemonsTypes[id] }
</div>
</div>
))
}
</div>
...
</div>
<div className="column description">
{ pokemonDescription }
</div>
</div>
)

Resources