Etheran
Etheran

Reputation: 61

Strategy pattern with React component

I'm trying to use the strategy pattern inside a react component to render different functions instead of using a switch case just for learning purposes but i'm not sure where to start.

Would it be a good way to do it?

    const renderField = () => {
        switch (field) {
            case 1:
                return first();
            case 2:
                return second();
            default:
                return third();
        }
    };

    return <div>{renderField()}</div>;

Upvotes: 3

Views: 4172

Answers (1)

Michel Vorwieger
Michel Vorwieger

Reputation: 722

you would just use React children. Strategy Pattern is a way to not need to change the base component but change some behaviour dynamically from the ouside.

const MyComponent = ({children}) => <div>{children}<div>

<MyComponent><FirstComponent></FirstComponent></MyComponent>

However if you want to pass in a children based on some other values e.g 1, 2, 3.

you could create a Object that holds their Relations to the components:

const componentMap = {1: <FirstComponent/>, 2: <SecondComponent/>}

and then use it like this:

<MyComponent>{componentMap[index]}</MyComponent>

Upvotes: 2

Related Questions