React select specific ref

698 views Asked by At

I need to select that one paragraph with class description when clicked on 'Click me' link, then I will add class to this paragraph.
I tried to do it with e.currentTarget + previousSibling, but it didn`t work.
How to do it in React TS?
My code:

import React, { useRef, useEffect, useState } from 'react';
import { Item } from '../types';


interface Props {
    handleData: (item: Item) => void;
}

const CartList = (props: Props) => {
    const description = useRef(null)
    const [items, setItems] = useState<Item[]>([]);

    const showMore = (e: Event) => {
        e.preventDefault();

        });
    };

    useEffect(() => {
        fetch(`./list.json`)
            .then((response) => response.json())
            .then((data) => setItems(data))
            .catch((error) => console.error(error));
    }, []);

    return (
        <main className="container">
            <ul className="row item-list">
                {items.map((item: Item, index: number) => (
                    <li key={item.id} className="col-xl-3 item">
                        <div className="item-wrap p-3">
                            <p
                                className="item-description"
                                ref={description}
                            >
                                {item.description}
                            </p>
                            <a href="." onClick={(e: any) => showMore(e)}>
                                Click me
                            </a>
                        </div>
                    </li>
                ))}
            </ul>
        </main>
    );
};

export default CartList;

2

There are 2 answers

0
Sam On

You could have something like

const [yourClass, setYourClass] = useState('Name Before')

with an onClick like onClick={setClicked('Name after')}, inside the button


And then just make sure the class is set to yourClass

0
Blablabla On

I know how to toggle class to element, but I don`t know, how to assign it to the correct element. Let say I have 5 elements and I click on button in first of them. The class should be assigned to the paragraph one, but React find the last existence of ref "description", so the class will be on last paragraph. And it is not correct.