How can I change the image and the color of the paragraph for the current box that I selected. I will appreciate any help. Thank you!
The code is below. https://stackblitz.com/edit/react-ts-gbc9dn?file=Child.js,App.js,Child.css
How can I change the image and the color of the paragraph for the current box that I selected. I will appreciate any help. Thank you!
The code is below. https://stackblitz.com/edit/react-ts-gbc9dn?file=Child.js,App.js,Child.css
You need to keep selectedPack in the state of parent component like: const [selectedPack, setSelectedPack] = useState(); and focusHandler should update this state on click.
Parent App.js will be like:
import * as React from 'react';
import { useState } from 'react';
import './style.css';
import Child from './Child';
const data = [
{
title: 'title one',
pack: 'one',
image: 'https://dummyimage.com/640x360/fff/aaa',
imageSelected: 'https://dummyimage.com/640x360/ccc/aaa',
},
{
title: 'title two',
pack: 'two',
image: 'https://dummyimage.com/640x360/ddd/aaa',
imageSelected: 'https://dummyimage.com/640x360/fff/eee',
},
{
title: 'title three',
pack: 'three',
image: 'https://dummyimage.com/640x360/fff/bbb',
imageSelected: 'https://dummyimage.com/640x360/aaa/aaa',
},
];
export default function App() {
const [selectedPack, setSelectedPack] = useState();
const focusHandler = (pack) => {
setSelectedPack(pack);
};
return (
<div>
{data.map(({ image, title, imageSelected, pack }) => {
return (
<Child
key={pack}
pack={pack}
image={image}
imageSelected={imageSelected}
title={title}
currentlySelected={selectedPack === pack}
focusHandler={focusHandler}
/>
);
})}
</div>
);
}
and Child.js will be like:
import * as React from 'react';
import './Child.css';
const Child = ({
title,
pack,
image,
imageSelected,
currentlySelected,
focusHandler,
}) => {
const focus = currentlySelected ? 'focus' : '';
const imageSrc = currentlySelected ? imageSelected : image;
return (
<div className="box" onClick={() => focusHandler(pack)}>
<p className={focus}>{title}</p>
<img src={imageSrc} />
</div>
);
};
export default Child;
This stackblitz is a working example of this usage.