score:0

export function mycomponent() {
  const images = [
    {
      image: 'http://www.example1.com/image1.jpg',
      title: 'title 1',
    },
    {
      image: 'http://www.example2.com/image2.jpg',
      title: 'title 2',
    },
    {
      image: 'http://www.example3.com/image3.jpg',
      title: 'title 3',
    },
  ];

  const [titles, settitles] = react.usestate([]);

  return (
    <div>
      <div>{titles}</div>

      <section classname="images">
        {images.map((image) => (
          <img
            style={{
              border: titles.includes(image.title) ? '3px solid black' : 'none',
            }}
            src={image.image}
            alt={image.title}
            onclick={() => {
              if (titles.includes(image.title)) {
                settitles(titles.filter((title) => title !== image.title));
              } else settitles([...titles, image.title]);
            }}
          />
        ))}
      </section>
    </div>
  );
}

score:1

i assume that you want to select one image at a time and display the title of it. so, here is a naive approach that you can adapt according to your situation.

const images = [
  { image: "https://via.placeholder.com/150", title: "title 1" },
  { image: "https://via.placeholder.com/150", title: "title 2" },
  { image: "https://via.placeholder.com/150", title: "title 3" },
];

function main() {
  const [selected, setselected] = react.usestate();

  return (
    <div>
      <div>{images[selected] && images[selected].title}</div>

      <section classname="images">
        {images.map((image, index) => (
          <img
            classname={index === selected ? "selected" : ""}
            key={`${index}${image.title}`}
            src={image.image}
            alt={image.title}
            onclick={() => setselected(index)}
          />
        ))}
      </section>
    </div>
  );
}

reactdom.render(<main />, document.getelementbyid("root"));
.selected {
  border: 5px solid black;
}
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root" />

so, you have one state, the selected index. for the classname part you look for the image's index, compare with the selected state then assign a class name according to that. for the title part, you are just grabbing the title by using the selected index with a conditional jsx.

but, using indices is not reliable. it would be better to have some unique ids for the images.


Related Query

More Query from same tag