2

I want to dynamically select a react component from a object with a key

import React, {useState, useEffect} from 'react'
import ComponentA from '@components/ComponentA';
import ComponentB from '@components/ComponentB';
  
const DynamicComponent: React.FC = ({key}) => {  
  const [Component, setComponent] = useState<any>();
  const COMPONENTS = {
    COMPONENT_A: ComponentA,
    COMPONENT_B: ComponentB,
  };

  useEffect(() => {
    if (key) setComponent(COMPONENTS[key])
  }, [key]);

  return Component ? React.createElement(Component) : null;
};

With this i get a type error on COMPONENTS[key]

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ COMPONENT_A: FC<{}>; }'.
No index signature with a parameter of type 'string' was found on type '{ COMPONENT_A: FC<{}>; }'.

How do i type this correctly?

3 Answers 3

1

You need define PropTypes for your component, also type of Key.

import React, {useState, useEffect} from 'react'
import ComponentA from '@components/ComponentA';
import ComponentB from '@components/ComponentB';

type Key = "COMPONENT_A" | "COMPONENT_B"

type Props = { key: Key }
  
const DynamicComponent: React.FC<Props> = ({key}) => {  
  const [Component, setComponent] = useState<any>();
  const COMPONENTS = {
    COMPONENT_A: ComponentA,
    COMPONENT_B: ComponentB,
  };

  useEffect(() => {
    if (key) setComponent(COMPONENTS[key])
  }, [key]);

  return Component ? React.createElement(Component) : null;
};
Sign up to request clarification or add additional context in comments.

Comments

1

You're missing default value for useState

You can use null as default value:

useState(null)

Like this:

 const [Component, setComponent] = useState<any>(null);

1 Comment

Thanks for looking into it, but that unfortunately does not solve the type error
1

I found the answer here: https://stackoverflow.com/a/55014391

Typing the COMPONENTS object fixed my problem.

import React, {useState, useEffect} from 'react'
import ComponentA from '@components/ComponentA';
import ComponentB from '@components/ComponentB';
  
const DynamicComponent: React.FC = ({key}) => {  
  const [Component, setComponent] = useState<any>();
  const COMPONENTS: {[key: string]: React.FC<any>} = {
    COMPONENT_A: ComponentA,
    COMPONENT_B: ComponentB,
  };

  useEffect(() => {
    if (key) setComponent(COMPONENTS[key])
  }, [key]);

  return Component ? React.createElement(Component) : null;
};

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.