skip to Main Content

When clicking on a button I want it to display a different style and map through an array of objects. But I can’t get past the first object. enter image description here
enter image description here

const handleHeroCard = () => {
  I am performing a findIndex function but it doesn't go past the second object in the array
}

2

Answers


  1. You are using your useState with [heroCard,setHeroCard] with default value of (page.page.data).

    when you call the function throught the button you are again setting the hero card to be only of data of 0 index.

    So,here basically your original array of data is replaced with only one data which will be of 0 index.

    Your original array of data is permanently replaced unless you restore it through your fetching mechanism.

    In order to get solution you can use two variables.

    one to store original array of data.

    another to get the desired data from original array.

    Login or Signup to reply.
  2. To achieve a button click that displays a different style and maps through an array of objects in React, you can utilize state to keep track of the selected index. Here’s an example component:

    jsx
    Copy code
    import React, { useState } from 'react';
    
    const YourComponent = () => {
      const data = {
        success: true,
        data: {
          pages: [
            {
              title: "FrontEnd Development with Class",
              document: "I am a Front End Web developer with a passion for building scalable, maintainable, and accessible web applications. I have a strong background in HTML, CSS, Javascript, and REACT. I am always looking for new challenges and opportunities to grow and learn."
            },
            // Add more objects to the array if needed
          ]
        }
      };
    
      const [selectedPageIndex, setSelectedPageIndex] = useState(0);
    
      const handleHeroCard = (index) => {
        setSelectedPageIndex(index);
      };
    
      return (
        <div>
          {data.data.pages.map((page, index) => (
            <div key={index} className={index === selectedPageIndex ? 'selected-style' : 'default-style'}>
              <h3>{page.title}</h3>
              <p>{page.document}</p>
              <button onClick={() => handleHeroCard(index)}>Click me</button>
            </div>
          ))}
        </div>
      );
    };

    export default YourComponent;
    In this example, selectedPageIndex is used to track the currently selected index. The handleHeroCard function updates this state on button click. CSS classes like ‘selected-style’ and ‘default-style’ can be used to apply different styles based on the selected index.

    Make sure to replace these class names with your actual CSS classes. Feel free to adjust the code to suit your specific requirements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search