Strategy pattern with React component

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>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top