ContextProvider => Context APi : Children dynamically rendered

Viewed 37

I have a function component named: Register. I use MUI (Material UI for ReactJS).

Inside it, I call 2 components: Step1 and Step2. Both use data collected through forms.

To simplify I don't post all the code.

<RegisterContextProvider>
    {activeStep + 1 === 1 && (<Step1 handleNext={handleNext} />)}
    {activeStep + 1 === 2 && (<Step2 handleNext={handleNext} handleBack={handleBack} />)}
</RegisterContextProvider>

When I click the "Next button" inside Step1, I go the next step of the MUI STEPPER component and render: Step2.

Step2 is rendered in the list of children of RegisterContextProvider, and Step1 disappears from the list, and then the data stored in the Step1 form is reinitialized.

Is there a way to wrap the components inside a higher level, like this:

<RegisterContextProvider>
    <Register/>
</RegisterContextProvider>

Thank You for advice

1 Answers

You can create a Register component that will receive an array of objects with the data of the step components and the index of the current step.

Example:

import React, {useMemo} from 'react';

const outOfBoundsOfStepsData = {
    Component: () => (<span>Index out of bounds of array</span>),
    props: {}
};

const Register = ({steps, index}) => {
    const {Component: Step, props} = useMemo(() => steps[index] || outOfBoundsOfStepsData, [steps, index]);

    return <Step {...props} />;
};

const Step1 = () => {
    // TODO
};

const Step2 = () => {
    // TODO
};

const App = () => {
    const steps = [
        {
            Component: Step1,
            props: {
                handleNext: () => console.log('TODO handleNext')
            }
        },
        {
            Component: Step2,
            props: {
                handleNext: () => console.log('TODO handleNext'),
                handleBack: () => console.log('TODO handleBack')
            }
        }
    ];

    const index = 0; // TODO

    return (
        <RegisterContextProvider>
            <Register steps={steps} index={index}/>
        </RegisterContextProvider>
    );
};
Related