I have a list of Image
components in my App
component. In the App
component, this list of Image
components is passed to the Display
component for rendering. Each Image
component has a prop that is a function that deletes the component from the UI. When there is only one rendered Image
left the in the App
, I want to dynamically update its class. Currently, I can keep track of how many images are open in App
with the useState variable oneImg
. I'm trying to figure out how, when oneImg === true
to update the className varaible cName
in App
.
// App.tsx
const [oneImg, setIsOneImg] = useState(false);
const [cname, setCname] = useState(() => {oneImg ? "singleImgClass" : "multiImgClass"}) // This doesn't seem to work
const images = [<Image key={0} className={cName} onRemove={remove()}/>, <Image key={1} className={cName} onRemove={remove()}/>]
<Display imgs={images} setIsOneImg={setIsOneImg}/>
// Display.tsx
function numberOfImages(imgs) {
return cards.filter((img) => {
return img.props.open;
}).length;
}
const Display = ({ imgs, setIsOneImg }) => {
setIsOneImg(numberOfImages(imgs) === 1);
return (
<div>
{imgs}
</div>
);
};
export default Display;
How can cName
be updated when oneImg
goes from false
to true
or vice versa?
CodePudding user response:
Since cName is calculated from oneImg you don't have to store it as a state, App will be rerendered when oneImg is updated and you can just define cName as a const:
const cName = oneImg ? "singleImgClass" : "multiImgClass";
should just work !