0

I have a menu. I want the menu items to open different components all with the same style and props.

So I need sth. like this in JSX:

<VARIABLE_HERE style={...} otherProp={'otherProp'}>

where VARIABLE_HERE is a variable i can set (e.g. FileView, SummaryView, ...).

1
  • This question is very generic. Can you be a bit more specific in what you want? Commented May 22, 2020 at 11:43

2 Answers 2

2
import component1 from '/component1';
import component2 from '/component2';

const availableComponents = {
  component1,
  component2
};

const MyComponent = (props) => {
  const chosenOne = 'component1';
  const DisplayedComponent = availableComponents[chosenOne];
  return <DisplayedComponent {...props} />;
};

set your choseOne in a condition.

Sign up to request clarification or add additional context in comments.

Comments

0

You can create FactoryComponent and inside of the factory component, you can send the VARIABLE_NAME as a prop then you can do what you need. You can check the below example.

FactoryComponent.jsx

const DynamicComponents = {
    fileView: FileView,
    summaryView: SummaryView
};

const FactoryComponent = (props) => {
    const Component = DynamicComponents[props.componentName] || null; 

    return <Component { ...props }/>
}

Then, you will add the your FactoryComponent to the place that you need. Hypothetically, I am going to use it in Main.jsx.

Main.jsx

const Main = () => {
    return <FactoryComponent componentName={VARIABLE_HERE} />
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.