Home > Software design >  how to control the state of many components
how to control the state of many components

Time:10-08

I have an api with which data comes about how many components there will be and what data will be stored in it, I generate these components through the map () method. Now I need that when I click on the image (which each component has), a class is added to this component, but at the moment I can only add an additional class to one element.

    
    const [favorite, setFavorite] = useState();

    // Function to add an additional class
    async function addFavoriteChanel(index) {
        if(favorite === index) { 
            setFavorite(0);
        } else {
            setFavorite(index)
       }
    }
    
    // Getting data from api
    async function getResponse() {
        let response = await fetch('https:api.json')
        let content = await response.json()
        setChanelData(content.channels)
    }


    useEffect(() => {
        getResponse();
    }, [])
    
    // visibleData it returns flickered data from api (Search engine, I did not add it here)
    // ...img src={star}... Clicking on this image will add it to your favorites
    <div className="container">
                    {Array.isArray(visibleData) ? visibleData.map((chanel, index) => {
                        return (
                            <div href={chanel.url} className="chanel__item" key={index}>
                                <img src={star} alt="star" onClick={() => addFavoriteChanel(index)} id={index} className={`star ${favorite === index  ? 'active' : ''}`} />
                                <img src={chanel.image} alt="" className="chanel__img" />
                                <div className="chanel__title"><div className="chanel__item-number">{chanel.number}. &nbsp;</div>{chanel.name_ru}</div>
                            </div> 
                        ) 
                    }) : null}
                </div>

I thought I could use an object in state and add keys for each component there, but I don’t understand how to do it correctly

I'd be happy to hear any advice. =)

CodePudding user response:

You should make the state an array, that way you can add multiple channels to favourites:

const [favorite, setFavorite] = useState([]);

// Function to add an additional class
function toggleFavoriteChanel(index) {
    setFavorite(prevState => {
       let returnArray = prevState;
       if(prevState.includes(index)){
          return returnArray.splice(prevState.indexOf(index), 1)
       }else{
          return [...returnArray, index]
       }
    }
}

and then you only need to change one more thing

<img src={star} alt="star" onClick={() => toggleFavoriteChanel(index)} id={index} className={`star ${favorite.includes(index)  ? 'active' : ''}`} />

now you can add and remove from favourites by pressing the image

CodePudding user response:

You need to split the content of .map into separate function component and declare state there

  • Related