How do I pass data when the x button is clicked? - reactjs

So I have a filter chip, and this filter chip is just passed a text body, and close function like so:
import CloseIcon from '#mui/icons-material/Close';
import "./FilterChip.css";
function FilterChip({textBody, onCloseClick}) {
return <div className="filter-chip">
Category: {textBody} <CloseIcon onClick={onCloseClick} className="filter-chip-close-button"/>
</div>
}
export default FilterChip;
I can render multiple filter chips in one page. How can I tell my parent component that the particular chip's x button has been clicked? Is it possible to pass this data on the onCloseClick function? I need to remove the chip once it's x button has been clicked, and I also need to uncheck it from my list of check boxes in my parent component. This is how I render the chips.
function renderFilterChips() {
const checkedBoxes = getCheckedBoxes();
return checkedBoxes.map((checkedBox) =>
<FilterChip key={checkedBox} textBody={checkedBox} onCloseClick={onChipCloseClick} />
);
}

You should pass an "identifier" for each chip and then use that identifier to find out "what" was clicked by the user. And then you can filter out the clicked chip.
function FilterChip({ textBody, onCloseClick, id }) {
const handleOnClose = (event) => {
onCloseClick(event, id);
};
return (
<div className="filter-chip">
Category: {textBody}{" "}
<CloseIcon onClick={handleOnClose} className="filter-chip-close-button" />
</div>
);
}
Now your onCloseClick should accept a new param id and handle the logic to remove the chip .
Hope it helps.

Sounds like you need checkedBoxes to be in state.
import { useState } from "react"
const initialBoxes = getCheckedBoxes()
function renderFilteredChips() {
const [ checkedBoxes, setCheckedBoxes ] = useState(initialBoxes)
}
Then implement a function to remove a checked box by its index (or if you have a unique key identifier that would be even better)
const onChipCloseClick = (indexToRemove) => {
setCheckedBoxes(state => state.filter((_, chipIndex) => chipIndex !== indexToRemove))
}
Then when you map over the chips, make sure the function that closes the chip has its index, effectively allowing each chip in state to filter itself out of state, which will re-render your chips for you.
import { useState } from "react"
const initialBoxes = getCheckedBoxes()
function renderFilteredChips() {
const [ checkedBoxes, setCheckedBoxes ] = useState(initialBoxes)
const onChipCloseClick = (indexToRemove) => {
setCheckedBoxes(state => state.filter((_, chipIndex) => chipIndex !== indexToRemove))
}
return <>
{checkedBoxes.map((checkedBox, index) => (
<FilterChip
key={index}
textBody={checkedBox}
onCloseClick={() => onChipCloseClose(index)}
/>
})
</>
}
Obligatory note that I haven't checked this and wrote it in Markdown, so look out for syntax errors (:

Related

Like Button with Local Storage in ReactJS

I developed a Simple React Application that read an external API and now I'm trying to develop a Like Button from each item. I read a lot about localStorage and persistence, but I don't know where I'm doing wrong. Could someone help me?
1-First, the component where I put item as props. This item bring me the name of each character
<LikeButtonTest items={item.name} />
2-Then, inside component:
import React, { useState, useEffect } from 'react';
import './style.css';
const LikeButtonTest = ({items}) => {
const [isLike, setIsLike] = useState(
JSON.parse(localStorage.getItem('data', items))
);
useEffect(() => {
localStorage.setItem('data', JSON.stringify(items));
}, [isLike]);
const toggleLike = () => {
setIsLike(!isLike);
}
return(
<div>
<button
onClick={toggleLike}
className={"bt-like like-button " + (isLike ? "liked" : "")
}>
</button>
</div>
);
};
export default LikeButtonTest;
My thoughts are:
First, I receive 'items' as props
Then, I create a localStorage called 'data' and set in a variable 'isLike'
So, I make a button where I add a class that checks if is liked or not and I created a toggle that changes the state
The problem is: I need to store the names in an array after click. For now, my app is generating this:
App item view
localStorage with name of character
You're approach is almost there. The ideal case here is to define your like function in the parent component of the like button and pass the function to the button. See the example below.
const ITEMS = ['item1', 'item2']
const WrapperComponent = () => {
const likes = JSON.parse(localStorage.getItem('likes'))
const handleLike = item => {
// you have the item name here, do whatever you want with it.
const existingLikes = likes
localStorage.setItem('likes', JSON.stringify(existingLikes.push(item)))
}
return (<>
{ITEMS.map(item => <ItemComponent item={item} onLike={handleLike} liked={likes.includes(item)} />)}
</>)
}
const ItemComponent = ({ item, onLike, liked }) => {
return (
<button
onClick={() => onLike(item)}
className={liked ? 'liked' : 'not-liked'}
}>
{item}
</button>
)
}
Hope that helps!
note: not tested, but pretty standard stuff

Inject Props to React Component

For security reasons, I have to update ant design in my codebase from version 3 to 4.
Previously, this is how I use the icon:
import { Icon } from 'antd';
const Demo = () => (
<div>
<Icon type="smile" />
</div>
);
Since my codebase is relatively big and every single page use Icon, I made a global function getIcon(type) that returns <Icon type={type}>, and I just have to call it whenever I need an Icon.
But starting from antd 4, we have to import Icon we want to use like this:
import { SmileOutlined } from '#ant-design/icons';
const Demo = () => (
<div>
<SmileOutlined />
</div>
);
And yes! Now my getIcon() is not working, I can't pass the type parameter directly.
I tried to import every icon I need and put them inside an object, and call them when I need them. Here's the code:
import {
QuestionCircleTwoTone,
DeleteOutlined,
EditTwoTone
} from '#ant-design/icons';
let icons = {
'notFound': <QuestionCircleTwoTone/>,
'edit': <EditTwoTone/>,
'delete': <DeleteOutlined/>,
}
export const getIcon = (
someParam: any
) => {
let icon = icons[type] !== undefined ? icons[type] : icons['notFound'];
return (
icon
);
};
My problem is: I want to put someParam to the Icon Component, how can I do that?
Or, is there any proper solution to solve my problem?
Thanks~
You can pass props as follows in the icons Object:
let icons = {
'notFound':(props:any)=> <QuestionCircleTwoTone {...props}/>,
'edit': (props:any)=><EditTwoTone {...props}/>,
'delete':(props:any)=> <DeleteOutlined {...props}/>,
}
And then if you will pass any prop to the Icon component then it will pass the prop to the specific icon component
let Icon = icons[type] !== undefined ? icons[type] : icons['notFound'];
return (<Icon someParam={'c'}/>)

How should I update individual items' className onClick in a list in a React functional component?

I'm new to React and I'm stuck trying to get this onClick function to work properly.
I have a component "Row" that contains a dynamic list of divs that it gets from a function and returns them:
export function Row({parentState, setParentState}) {
let divList = getDivList(parentState, setParentState);
return (
<div>
{divList}
</div>
)
}
Say parentState could just be:
[["Name", "info"],
["Name2", "info2"]]
The function returns a list of divs, each with their own className determined based on data in the parentState. Each one needs to be able to update its own info in parentState with an onClick function, which must in turn update the className so that the appearance of the div can change. My code so far seems to update the parentState properly (React Devtools shows the changes, at least when I navigate away from the component and then navigate back, for some reason), but won't update the className until a later event. Right now it looks like this:
export function getDivList(parentState, setParentState) {
//parentState is an array of two-element arrays
const divList = parentState.map((ele, i) => {
let divClass = "class" + ele[1];
return (
<div
key={ele, i}
className={divClass}
onClick={() => {
let newParentState =
JSON.parse(JSON.stringify(parentState);
newParentState[i][1] = "newInfo";
setParentState(newParentState);}}>
{ele[0]}
</div>
)
}
return divList;
}
I have tried to use useEffect, probably wrong, but no luck. How should I do this?
Since your Row component has parentState as a prop, I assume it is a direct child of this parent component that contains parentState. You are trying to access getDivList in Row component without passing it as a prop, it won't work if you write your code this way.
You could use the children prop provided by React that allow you to write a component with an opening and closing tag: <Component>...</Component>. Everything inside will be in the children. For your code it would looks like this :
import React from 'react';
import { render } from 'react-dom';
import './style.css';
const App = () => {
const [parentState, setParentState] = React.useState([
['I am a div', 'bg-red'],
['I am another div', 'bg-red'],
]);
React.useEffect(
() => console.log('render on ParentState changes'),
[parentState]
);
const getDivList = () => {
return parentState.map((ele, i) => {
return (
<div
key={(ele, i)}
className={ele[1]}
onClick={() => {
// Copy of your state with the spread operator (...)
let newParentState = [...parentState];
// We don't know the new value here, I just invented it for the example
newParentState[i][1] = [newParentState[i][1], 'bg-blue'];
setParentState(newParentState);
}}
>
{ele[0]}
</div>
);
});
};
return <Row>{getDivList()}</Row>;
};
const Row = ({ children }) => {
return <>{children}</>;
};
render(<App />, document.getElementById('root'));
And a bit of css for the example :
.bg-red {
background-color: darkred;
color: white;
}
.bg-blue {
background-color:aliceblue;
}
Here is a repro on StackBlitz so you can play with it.
I assumed the shape of the parentState, yu will have to adapt by your needs but it should be something like that.
Now, if your data needs to be shared across multiple components, I highly recommand using a context. Here is my answer to another post where you'll find a simple example on how to implement a context Api.

Paypal button cannot read new React state. How to work with dynamic values and paypal in React?

I'm currently working on the checkout page of an application where a user can purchase up to three items at one of three prices chosen by the user (this is mostly being done as an experiment). When the user chooses a price by clicking a button this triggers a setState and a new price is stored to the state. When doing console.log I see the new state has been set, but upon checkout it appears the state resets to its initial value. I can't tell why and have no idea where to begin on this one. I imagine on initial render paypal is keeping the initial state it was passed and needs to be rerendered when the new state is set, but not sure how to go about this or even if this is the problem. Any help or guidance is appreciated.
I'm using the #paypal/react-paypal-js library for this paypal implementation, but am welcome to alternative suggestions.
Here is the code I'm using but cut down relevant sections:
import React, {useState, useRef, useEffect} from 'react';
import { PayPalButtons, usePayPalScriptReducer } from "#paypal/react-paypal-js";
import PriceButton from './PriceButton.jsx';
import NumberItemButton from './NumberItemButton';
import {priceOptions, amountItems} from './PriceOptions';
const PaymentPage = () => {
const [isLoading, setIsLoading] = useState(false);
const [payAmount, setPayAmount] = useState('5.00');
const [itemAmount, setItemAmount] = useState('1');
const payPalOptions = { //Note: This is used in the higher level component PayPalScriptProvider
"client-id": `${process.env.REACT_APP_PAYPAL_CLIENT_ID}`,
currency: "USD",
intent: "capture",
};
const createOrder = (data, actions) => { //This will show the initial state when triggered
return actions.order.create({
purchase_units : [
{
amount: {
value: payAmount //This stays at the initial State of '5.00' despite the newState being set
}
}
]
})
};
const onApprove = (data, actions) => {
return actions.order.capture().then(function(orderData) {
console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
let transaction = orderData.purchase_units[0].payments.captures[0];
alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
}
)};
const onError = (error) => {
console.log(error)
}
console.log(payAmount) //Note: This will show the new State
return (
<div>
<h1>Purchase</h1>
<label> Choose number of items
<div>
{amountItems.map((item, index) => {
return <NumberItemButton key={index} setItemAmount={setItemAmount} amount={item.amount} />
})}
</div>
</label>
<label> Pick a price
<div>
{priceOptions.map((item, index) => {
return <PriceButton key={index} itemAmount={itemAmount} setPayAmount={setPayAmount} price={item.price} />
})}
</div>
</label>
<PayPalButtons
createOrder={(data, actions) => createOrder(data, actions)}
onApprove={(data, actions) => onApprove(data, actions)}
onError={onError}
/>
</div>
);
}
export default PaymentPage;
I'll also add the price button component incase the issue is there
const PriceButton = ({itemAmount, setPayAmount, price}) => { //itemAmount is the amount customer buys, price is the value passed through on the mapping function
const multPrice = (itemAmount * price).toFixed(2);
const withTaxPrice = (parseInt(multPrice) + .5).toFixed(2).toString();
return (
<button onClick={() => setPayAmount(withTaxPrice)}>${multPrice}</button>
)
}
export default PriceButton;
Appreciate any help!
I came back to this with a fresh pair of eyes and found the solution (though I'm not sure if it's the best one).
The issue is when the Paypal button renders it pulls in the initial state that is passed through, but it needs to be rerendered when a new state is passed.
My solution to this was to pass a forceReRender={[payAmount]} within the PaypalButtons component. This rerenders the Paypal button upon update to the price state and allows me to pass an updated value.
Hope this helps others!
I found a better solution. Just use useRef and access the ref.current value!

event from onSelect returning null

So I have this weird problem (and I am sorry a newbie on this still) but I have a dropdown list that I want to be able to select from and pass back to a form to submit. it works fine when I do the drop down line items manually, but when I retrieve it from the backend and then map, and try to handle the onSelect but the event on onSelect keeps returning null - so confused - do you see anything obvious in this code?
import React, { useEffect, useState } from 'react';
import { useHttpClient } from '../hooks/http-hook';
import { validate } from '../util/validators';
import 'bootstrap/dist/css/bootstrap.min.css';
import DropdownButton from 'react-bootstrap/DropdownButton';
import Dropdown from 'react-bootstrap/Dropdown';
import './Input.css';
const Select = props => {
console.log('props.id=' + props.id);
console.log('props.label=' + props.label);
const [selValue, setSelValue] = useState('');
const { isLoading, error, sendRequest, clearError } = useHttpClient();
const [loadedFoodgroups, setLoadedFoodgroups] = useState([]);
useEffect(() => {
const fetchFoodgroups = async () => {
try {
const responseData = await sendRequest('http://localhost:5000/api/foodgroups')
setLoadedFoodgroups(responseData);
console.log('ResponseData' + JSON.stringify(responseData));
} catch (err) { }
};
fetchFoodgroups();
}, [sendRequest]);
const handleSelect = (event) => {
event.preventDefault();
console.log('Select.js: handleSelect- event e=' + event.target.value);
setSelValue(event.target.value);
}
return (
<React.Fragment>
<DropdownButton
className="form-control__select"
alignRight
title="Foodgroups"
id="dropdown-menu-align-right"
onSelect={handleSelect}
value={selValue}
>
<label htmlFor={props.id}>{props.label}</label>
{loadedFoodgroups.map(selectOptions => (
<Dropdown.Item
key={selectOptions.id}
className="form-control__select"
eventkey={selectOptions.id}>{selectOptions.name}
</Dropdown.Item>
))}
</DropdownButton>
</React.Fragment>
);
};
export default Select;
While the underlying issue is answered in some other questions (kind of), you have a few things you have to change, so here is a more specific answer for you:
First, the signature of onSelect is (eventKey, event) => ..., but in my testing the second param is not useful (target is null). So even if you switch to using the second param in your handler, it probably won't work. Instead, most people seem to be using the eventKey param like this:
const handleSelect = eventKey => {
event.preventDefault();
setSelValue(eventKey);
}
Which would probably meet your needs.
Before this will work for you, there are three typos to fix:
<Dropdown.Item
key={selectOptions._id}. <--you have ".id" i your code but the data is "._id"
className="form-control__select"
eventKey={selectOptions.name} <--you have "eventkey", with lowercase "k",
// should be upper case.
// You probably want the ".name" property here rather than
// "id", this is what will be passed into "onSelect"
>
So if you change your handler to use first param as eventKey and fix typos above, you should be able to set the state to the value selected from the dropdown button.

Resources