How to add two different components on click of each other in react-native

43 Views Asked by At

I have a component StatusBoxComponent, which has two status's: Break-In and Break-out,

So Initially, Break-In box will be seen on opening this screen.

Now what I wanted is that, as I press Break-in box, immediately below Break-out box should come, and on this Break-out box, I again wanted to press this, so that Break-in box comes below this. And this process should go on.

const AttendanceScreen = (props: any) => {

    const [inState, setInState] = useState([<View />]);
    
    const breakOutClick = () => {
        setInState([
            ...inState,
            <>
                <StatusBoxComponent
                    status={'Break-In'}
                    breakIn={breakInClick}      // Point 3
                />
                {inState}
            </>,
        ]);
    };

    const breakInClick = () => {
        setInState([
            ...inState,
            <>
                <StatusBoxComponent
                    status={'Break-Out'}
                    breakIn={breakOutClick}      // Point 2
                />
                {inState}
            </>,
        ]);
    };

    return (
        <>
            <StatusBoxComponent
                status={'Break-In'}
                breakIn={breakInClick}      // Point 1
            />
            {inState}
        </>
    );
};

But, what's happening is, when initially I press break-in, one break-out box is coming, but when I click on this break-out, then instead of adding new box below, it is replacing the current box. And when clicked on the initial break-in box, then more than 1 break-in boxes are getting added below.

I don't know where in my logic am I going wrong.

1

There are 1 best solutions below

2
glinda93 On

Storing components inside state is generally a bad idea, when you can manage your state with serializable values.

const AttendanceScreen = (props: any) => {

    const [statuses, setStatuses] = useState(['Break-In']);

    
    
    const breakOutClick = () => {
        setStatuses([
            ...statuses,
            'Break-In',
        ]);
    };

    const breakInClick = () => {
        setStatuses([
            ...statuses,
            'Break-Out',
        ]);
    };

    return (
        <>
            {statuses.map((status, index) => (
                 <StatusBoxComponent
                     key={index}
                     status={status}
                     breakIn={breakInClick}      // Point 1
                 />
            )}
        </>
    );
};