Next.js Discord

Discord Forum

Next.js add tailwind className to cloned child without wrapping it

Unanswered
Chinese Alligator posted this in #help-forum
Open in Discord
Chinese AlligatorOP
Hi, I have this component and I would like to not have a div wrapping the children to avoid display conflicts but I don't find any way to add a className to it event by cloning
import React, {useEffect, useState} from 'react';

type Props = {
    delay: number;
    children: React.ReactNode;
}

const ProgressiveDisplay = ({ delay, children }: Props) => {
    const [state, setState] = useState<number>(0);
    const [elements, setElements] = useState<React.ReactNode[]>([]);

    useEffect(() => {
        setElements(React.Children.toArray(children));
    }, [children]);

    useEffect(() => {
        const interval = setInterval(() => {
            setState((prevIndex) => prevIndex + 1);
        }, delay);

        return () => clearInterval(interval);
    }, [delay]);

    return (
        <>
            {elements.map((child, index) => {
                if (React.isValidElement(child)) {
                    return <div key={index} className={`${index <= state ? 'opacity-100' : 'opacity-0'} duration-500`}>{child}</div>;
                }
                return child;
            })}
        </>
    );
}

export default ProgressiveDisplay;

16 Replies

Chinese AlligatorOP
Nobody ???
Northern Wheatear
I didn't understand your question to be honest. Do you want to pass your className to child?
@Northern Wheatear I didn't understand your question to be honest. Do you want to pass your className to child?
Chinese AlligatorOP
I want to pass 'opacity-100' : 'opacity-0' to child
@Chinese Alligator I want to pass 'opacity-100' : 'opacity-0' to child
You seem to have already done that
@Anay-208 You seem to have already done that
Chinese AlligatorOP
I don't want to use <div> but #Unknown Channel{child}</>
nothing should wrap child
thats not possible. to add a className, div elements needs to be there
Northern Wheatear
If your child element can accept className then its possible
Something like this
return (
        <>
            {elements.map((Child, index) => {
                if (React.isValidElement(Child)) {
                    return <Child key={index} className={`${index <= state ? 'opacity-100' : 'opacity-0'} duration-500`} />;
                }
                return Child;
            })}
        </>
    );
Note that Child starts with capital letter C
I think this should be possible
Chinese AlligatorOP
@Anay-208 thats not possible. to add a className, div elements needs to be there
Chinese AlligatorOP
Can't use div it destroys the layout
@Chinese Alligator Opacity is not applied to cloned element
Varied Thrush
pass the div than and give it classname of parent element if dont want to mess the ui