Toggling actions individually in cards mapped over - reactjs

I have cards that are mapped over They all have a toggle button menu and Im trying to figure out how to target the menu's individually since they are controlled by a single part of the state Im not even sure this is possible. But I think it should be right? I have created a simple working example here. Im not sure if I can use the ID of them to target them individually but im not sure how to implement that. Any advice would be helpful thanks!

1) First of all you can't control all state of Items with single boolean state, You can create open as an array and then initially set it as false.
const [open, setOpen] = useState(Array.from(Items, () => false));
2) When you want to toggle particular element then you can use index
onClick={() => toggle(idx)}
3) Then you have to handle 2 cases where you update newOpenState
case: 1: when you update respective state after you click on the button. In this case you are just toggling the value which is present at the index idx
<Button
isOpen={open[idx]}
onClick={() => toggle( idx )}
style={{
width: "30px",
height: "30px",
marginTop: "25px",
marginLeft: "10px"
}}
/>
case 2: When you externally providing the value
<Col
md="12"
onClick={() => toggle( idx, false )}
className="editCol"
>
So these two cases are covered by using a single expression as:
newOpenState[index] = value ?? !newOpenState[index];
what above statement means is if the value is provided(case 2) then you just have to assign the value to newOpenState[index]. If you haven't provided the value(case 1) then it will be undefined, and you have to just toggle the value of newOpenState[index]. I've used using Nullish coalescing operator (??) you can assign the right hand side value of ?? if left hand side of value is undefined or null.
CODE
import "./styles.css";
import { Card, Button, Col, Row } from "reactstrap";
import { useState } from "react";
const Items = [
{
name: "Test 1",
ID: 1234
},
{
name: "Test 2",
ID: 4321
},
{
name: "Test 3",
ID: 3421
}
];
export default function App() {
const [open, setOpen] = useState(Array.from(Items, () => false));
const toggle = (index, value) => {
const newOpenState = [...open];
newOpenState[index] = value ?? !newOpenState[index];
setOpen(newOpenState);
};
return (
<>
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
<div style={{ display: "flex", justifyContent: "space-between" }}>
{Items.map((item, idx) => (
<Card
key={idx}
style={{
border: "solid",
borderColor: "#00000",
margin: "5px",
width: "150px",
display: "flex",
justifyContent: "center"
}}
>
<h1>{item.name}</h1>
<span style={{ display: "flex" }}>
{!open[idx] ? (
<Button
isOpen={open[idx]}
onClick={() => toggle(idx)}
style={{
width: "30px",
height: "30px",
marginTop: "25px",
marginLeft: "10px"
}}
>
...
</Button>
) : (
<Card
style={{
border: "solid 1px",
borderColor: "#00000",
margin: "5px"
}}
>
<Row>
<Col md="12" className="closeMenu">
<span className="X" onClick={() => toggle(idx, false)}>
X
</span>
</Col>
</Row>
<Row>
<Col
md="12"
onClick={() => toggle(idx, false)}
className="editCol"
>
<span
className="editName"
onClick={() => setOpen(item.ID)}
>
Edit Name
</span>
</Col>
</Row>
<Row>
<Col md="12">
<span
className="deleteForm"
onClick={() => handleFormDelete(item.ID)}
>
Delete
</span>
</Col>
</Row>
</Card>
)}
</span>
</Card>
))}
</div>
</>
);
}

Related

react-table : How can I keep visible globalFilteredRows after editing my data?

I'm using v7 of react-table.
My issue is I have can set global filter but when i update my data it shows all my data and don't keep my filtered data.
How can I keep my filtered data visible when i want to update my react-table data?
const TableSearchFilter = ({ preGlobalFilteredRows, globalFilter, setGlobalFilter }) => {
const count = preGlobalFilteredRows.length
return (
<div style={{ textAlign: "right", marginBottom: '10px' }}>
<MaterialUI.FormControl sx={{ m: 1, width: '250px' }} variant="outlined">
<MaterialUI.Input
sx={{ fontSize :'12px' }}
value={globalFilter || ""}
onKeyDown={(e) => {
if (e.keyCode ==13) {
e.preventDefault()
}
}}
onChange={(e) => {
setGlobalFilter(e.target.value)
}}
startAdornment={<i className="fas fa-search" style={{ marginRight:'10px' }}></i>}
placeholder={`${count} référence${count > 0 ? 's' : ''}`}
/>
</MaterialUI.FormControl>
</div>
)
}
in my app.js
<Table columns={columns} data={data} />

How to keep the checkbox state saved after page refresh?

I am making a product comparison page. I am trying to keep the checkbox checked after page refresh. Actually I have a products page where each product has a checkbox beneath it. When I click the checkbox, that specific product is added to local Storage + comparison page which I have made. But when I refresh the page, that product is saved but checkbox is unchecked but I want to keep checkbox checked and if checkbox is unchecked, that specific item should be removed from comparison page. How do I solve this query. I have tried several times but not able to do this?? Below is my code
function Home()
{
let history = useHistory()
const getLocalItems = () => {
let compare = localStorage.getItem('compare')
console.log(compare)
if(compare){
return JSON.parse(localStorage.getItem('compare'))
}
else{
return []
}
}
const [comparison,showcomparison] = useState(getLocalItems())
const [item,setItems] = useState()
const [show,setShow] = useState(false)
function onAdd(record){
const exist = comparison.find((x) => x.id === record.id)
if(exist){
showcomparison(comparison.map((x) => x.id === record.id ? {...exist, quantity: exist.quantity+1} : x)
);
}
else
{
showcomparison([...comparison,{...record,quantity: 1}])
}
}
useEffect(() => {
localStorage.setItem('compare',JSON.stringify(comparison))
}, [comparison])
const removeAll = () => {
showcomparison([])
}
return(
<div className="Home">
{
records.map(record => {
return(
<div className='container' key={record.id} onAdd = {onAdd}>
<div className='row'>
<div className='col-xl-3'>
<img style={{width: '100%', height: 'auto'}} src={record.img1} alt=""/><br></br>
<input type='checkbox' value={record.img1} onChange={() => onAdd(record)} style={{paddingRight: '30%'}}/>Compare
</div>
<div className='col-xl-4'>
<p style={{textAlign: 'left', fontWeight: 'bold', fontSize: '18px'}}>{record.title}</p>
<p style={{textAlign: 'left', fontWeight: 'bold', fontSize: '18px'}}>{record.title2}</p>
<p style={{textAlign: 'left', fontWeight: 'bold', fontSize: '18px'}}>{record.title3}</p>
<p style={{textAlign: 'left', fontSize: '15px'}}>MFG#: {record.MFG} | CDW#: {record.CDW}</p>
<p style={{fontWeight: '650', textAlign: 'left'}}>Laptop Type: {record.Type}</p>
<p style={{fontWeight: '650',textAlign: 'left'}}>Screen size: {record.size}</p>
<p style={{fontWeight: '650',textAlign: 'left'}}>Processor Type: {record.ptype}</p>
<p style={{fontWeight: '650',textAlign: 'left'}}>Processor Speed: {record.pspeed}</p>
<p style={{fontWeight: '650',textAlign: 'left'}}>Hard Drive Capacity: {record.capacity}</p>
</div>
<div className='col-xl-3'>
<ul>
<li style={{color: 'green', marginBottom: '1px', textAlign: 'left', fontSize: '13.5px', fontWeight: '640'}}><p>{record.Availability}</p></li>
</ul>
<p style={{fontSize: '13px', textAlign: 'left'}}>Ships today if ordered within 6 hrs 21 mins</p>
<h4 style={{textAlign: 'left', fontFamily: '"Source Serif Pro",serif', fontWeight: 'bold'}}>{record.price}</h4>
<p style={{textAlign: 'left'}}>Advertised Price</p>
<div className='input-group'>
<button type='button' onClick={handleDecrement} className='input-group-text'>-</button>
<div className="form-control text-center"> {quantity} </div>
<button type='button' onClick={handleIncrement} className='input-group-text'>+</button>
</div><br></br>
<button style={{width: '100%', background: '#150404', color: 'white', fontSize: '17.5px', fontWeight: '600', height: '18%'}}>Add to Cart</button>
</div>
</div><hr></hr>
</div>
)
})
}
You can use useRef on the input checkbox, use the following property to set it checked or unchecked.
checkRef.current.checked=false
<input type='checkbox' ref={checkRef} value={record.img1} onChange={() =>
onAdd(record)} style={{paddingRight: '30%'}}/>Compare
use the checkRef.current to change the value with useState.

Card Text alignment in react Card Bootstrap

I have following code for creating a grid of cards , but the LINK button at the bottom is not aligned in all the cards. What do I need to change to get all the link buttons aligned in all the card at the bottom right. Please see the image at the bottom, I would like all the select button to be horizontally aligned with other cards in the row.
<Row xs={1} md={4} className="g-4">
{MilitaryFormsType.map((e, idx) => (
<Col>
<Card border="#f7f7f7" style={{ width: '18rem', height: '18rem', whiteSpace: 'pre-wrap' }}>
<Card.Body>
<Card.Title>{e.name}</Card.Title>
<Card.Text >{e.Description}</Card.Text>
<Link to={e.link} >
<Button variant="primary" style={{ backgroundColor: "#aa92df", borderStyle: "none", float: "right" }}>Select</Button>
</Link>
</Card.Body>
</Card>
</Col>
))}
</Row>
What I understand from a problem is you want to move the button on the right bottom of all cards.
You can use position "relative" on the body and for link position "absolute".
<Card.Body style={{ position: "relative" }}>
<Card.Title>{e.name}</Card.Title>
<Card.Text>{e.Description}</Card.Text>
<Link to={e.link} style={{ position: "absolute", bottom: 0, right: 0 }}>
<Button
variant="primary"
style={{
backgroundColor: "#aa92df",
borderStyle: "none",
float: "right",
}}
>
Select
</Button>
</Link>
</Card.Body>
**1. Try this one if using wrap it's possible **
<Card.Body>
<Card.Title>{e.name}</Card.Title>
<Card.Text >{e.Description}</Card.Text>
<Link to={e.link} >
<div style={{ text-align:center }}>
<Button variant="primary" style={{ backgroundColor: "#aa92df", borderStyle: "none"}}>Select</Button>
</div>
</Link>
</Card.Body>
Actually you can dynamically control the height of Card.Title, Card.Text and others using javascript. Below is the code of how you can make all the heights the same so the cards are aligned while containing all the data without overflowing. The principle is basically to set all the cards' heights equal to the height of the longest card. Below is the code:
const [cardHeight, setCardHeight] = useState(null);
const getMaxHeightTitle = (elements) => {
let titleHeights = Array.prototype.map.call(elements, (element, i) => {
return element.offsetHeight;
});
return Math.max(...titleHeights);
}
const setMaxContent = (elements) => {
Array.prototype.map.call(elements, (element, i) => {
element.style.height = 'max-content';
});
}
const setMaxHeightTitle = useCallback((elements, h) => {
Array.prototype.map.call(elements, (element, i) => {
if (element.offsetHeight !== cardHeight) {
element.style.height = cardHeight + 'px'
}
});
}, [cardHeight]);
const resizeCardTitle = useCallback(() => {
setMaxContent(document.getElementsByClassName('card-title h5'));
titleHeight = getMaxHeightTitle(document.getElementsByClassName('card-title h5'));
setCardHeight(titleHeight)
setMaxHeightTitle(document.getElementsByClassName('card-title h5'), titleHeight);
}, [setMaxHeightTitle]);
useEffect(() => {
window.addEventListener('load', resizeCardTitle);
window.addEventListener('resize', resizeCardTitle);
return () => {
window.removeEventListener('load', resizeCardTitle);
window.removeEventListener('resize', resizeCardTitle);
}
}, [cardHeight, resizeCardTitle]);
useEffect(() => {
resizeCardTitle();
}, [resizeCardTitle])

Change the display based on state from other component

So I have this custom collapse where I switch between 2 styles of displaying based on this const [disabled, setDisabled] = useState(true); state. Then I use this custom collapse on another component where after I click on a button I will want to change to another style of display which is the 3rd style of display. How exactly do I get the state then change it on the original component?
Here's the custom collapse in ./CustomCollapse.js
const CustomCollapse = (props) => {
const [disabled, setDisabled] = useState(true);
return (
<StyledCollapse onChange={() => setDisabled(prev => !prev)}>
<AntCollapse.Panel
header={props.header}
key="1"
showArrow={false}
bordered={false}
extra={
<span>
<span style={{ color: "#0076de", float: "right" }}>
// Here's where I wanna add the 3rd style
{disabled ? <div id={styles.themeBox}><p>+10</p></div> : <img src={arrowDownIcon} alt="" style={{height:'1.2em', marginLRight:'10px', width:'auto', objectFit:'contain'}} />}
</span>
</span>
}
>
{props.children}
</AntCollapse.Panel>
</StyledCollapse>
);
};
Here's where I want to change the state in ./FollowTelegram.js:
import AntCollapse from './CustomCollapse';
let [followed, setFollowed] = useState(false);
const setFollowed = () => {
setFollowed(prev => !prev)
}
// {...other code}
<AntCollapse id={styles.telegramHeader1} header="Follow XXX on Telegram Announcement Channel">
<Row type='flex' align='middle' justify='center'>
<Button href={links[0]} target="_blank" style={buttonStyle1} onClick={() => setClicked(false)}>
<Icon type="link" style={{ color: '#fff' }} theme="outlined" />
Subscribe
</Button>
</Row>
<span className={styles.greyLine}> </span>
<Row type='flex' align='middle' justify='center'>
//Here's where I wanna change followed to true
<Button onClick={setFollowed} style={buttonStyle2} disabled={clicked}>Continue</Button>
<Button type='text' style={{color:'#EB7B59', border:'#f7f7f7', background:'#f7f7f7',height: "2em", fontSize:'16px', margin:'10px 0 0 10px'}}>Cancel</Button>
</Row>
</AntCollapse>
But how can I pass the state to ./CustomCollapse to know and change the style?
You can pass the disabled value to the child component (CustomCollapse ) by adding a property.
import React, { useState, useEffect } from 'react'
const CustomCollapse = (props) => {
const [disabled, setDisabled] = useState(true);
useEffect(() => {
setDisabled(props.isDisabled)
}, [props.isDisabled])
return (
<StyledCollapse onChange={() => setDisabled(prev => !prev)}>
<AntCollapse.Panel
header={props.header}
key="1"
showArrow={false}
bordered={false}
extra={
<span>
<span style={{ color: "#0076de", float: "right" }}>
// Here's where I wanna add the 3rd style
{disabled ? <div id={styles.themeBox}><p>+10</p></div> : <img src={arrowDownIcon} alt="" style={{ height: '1.2em', marginLRight: '10px', width: 'auto', objectFit: 'contain', float: 'left' }} />}
</span>
</span>
}
>
{props.children}
</AntCollapse.Panel>
</StyledCollapse>
);
};
and in the parent component
import AntCollapse from './CustomCollapse';
//inside your parent component
let [followed, setFollowed] = useState(false);
const [disabledCollapse, setDisabledCollapse] = useState(true)
// {...other code}
const toggleDisabledCollapse = () => {
setDisabledCollapse(prev => !prev)
}
return <AntCollapse isDisabled={disabledCollapse} id={styles.telegramHeader1} header="Follow XXX on Telegram Announcement Channel">
<Row type='flex' align='middle' justify='center'>
<Button href={links[0]} target="_blank" style={buttonStyle1} onClick={() => setClicked(false)}>
<Icon type="link" style={{ color: '#fff' }} theme="outlined" />
Subscribe
</Button>
</Row>
<span className={styles.greyLine}> </span>
<Row type='flex' align='middle' justify='center'>
//Here's where I wanna change followed to true
<Button onClick={toggleDisabledCollapse} href={links[0]} target="_blank" style={buttonStyle2} disabled={clicked}>Continue</Button>
<Button type='text' style={{ color: '#EB7B59', border: '#f7f7f7', background: '#f7f7f7', height: "2em", fontSize: '16px', margin: '10px 0 0 10px' }}>Cancel</Button>
</Row>
</AntCollapse>

How to update height prop with useRef in React?

I need to dynamically define the size of HTML element and set its height to component. I tried to do this with useRef but it doesn't work as expected because of state which contains the previous value (not the current one). Could someone help me with this?
And here's the link: CodeSandBox https://codesandbox.io/s/happy-water-fzqk8?file=/src/App.js
The below code works fine but there's hardcored variable HEIGHT which defines the height of a tab. My task is to make the height dynamic
import { useState } from 'react';
const HEIGHT = {
0: 200,
1: 400,
2: 800,
}
function App() {
const [tab, setTab] = useState(0);
const switchTab = (id) => {
setTab(id);
};
return (
<div
style={{
margin: '100px auto',
backgroundColor: 'pink',
width: '400px',
overflow: 'hidden',
height: HEIGHT[tab], // need this to be dynamic not hardcored
}}
>
<div>
{tab === 0 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 1</h2>
<input />
<button onClick={() => switchTab(1)}>Go to tab 2</button>
<p>Some text here</p>
</div>
)}
{tab === 1 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 2</h2>
<input />
<button onClick={() => switchTab(0)}>Go to tab 1</button>
<button onClick={() => switchTab(2)}>Go to tab 3</button>
<p>
Some more text here. Some more text here. Some more text here. Some more text here.
Some more text here. Some more text here. Some more text here
</p>
</div>
)}
{tab === 2 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 3</h2>
<input />
<button onClick={() => switchTab(0)}>Go to tab 1</button>
<button onClick={() => switchTab(1)}>Go to tab 2</button>
</div>
)}
</div>
</div>
);
}
What I tried:
Added useRef and state which holds the element height
const elRef = useRef(0);
const [height, setHeight] = useState(elRef.current.offsetHeight);
Added function which calculates the size of an element and then sets it to state variable
const resizeHeight = useCallback(() => {
const size = elRef.current.offsetHeight;
setHeight(size)
}, [elRef]);
Added state Height to styles this way
<div
style={{
margin: '100px auto',
backgroundColor: 'pink',
width: '400px',
overflow: 'hidden',
height: height, // it should be the element size
}}
>
It doesn't work((
Here's the link...with the state height - undefined
https://codesandbox.io/s/objective-brown-zq7ih?file=/src/App.js
You can easily update your elRef reference in the switchTab handler without using useEffect and any useCallback hooks:
const elRef = useRef(0);
const SwitchTab = (id) => {
setTab(id);
setHeight(elRef.current.offsetHeight)
};
Now pass the elRef to the ref property of your target div:
return (
<div
style={{
margin: '100px auto',
backgroundColor: 'pink',
width: '400px',
overflow: 'hidden',
height: HEIGHT[tab],
}}
>
<div ref={elRef}> // ------------------------> added here
{tab === 0 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 1</h2>
<input />
<button onClick={() => switchTab(1)}>Go to tab 2</button>
<p>Some text here</p>
</div>
)}
{tab === 1 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 2</h2>
<input />
<button onClick={() => switchTab(0)}>Go to tab 1</button>
<button onClick={() => switchTab(2)}>Go to tab 3</button>
<p>
Some more text here. Some more text here. Some more text here. Some more text here.
Some more text here. Some more text here. Some more text here
</p>
</div>
)}
{tab === 2 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 3</h2>
<input />
<button onClick={() => switchTab(0)}>Go to tab 1</button>
<button onClick={() => switchTab(1)}>Go to tab 2</button>
</div>
)}
</div>
</div>
);

Resources