How to change the image and the style of a p tag when click on a current child div? react

Viewed 29
1 Answers

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.

Related