Search code examples
javascriptreactjsstyled-components

With React, is it possible to have a propType to specify the DOM element type?


I would like to create a React UI-Compoment for Typography. Where the component can be passed a propType to specify which element type should be rendered or

Perhaps a propType used like: as="span" or as="p"

Is this type of dynamic element type definition possible with React or do I need to do something less elegant and have a Switch statement with two types or return statements?

example: `if (this.props.p) {return <p>....</p>}

Example using this proposed component:

<MyC as="span">Hello World</MyC>
<MyC as="p">Hello World</MyC>

Solution

  • You could use React.createElement() as such:

    class MyC extends Component {
      state = {
        ready: false,
      };
    
      componentDidMount() {
        this.el = React.createElement(this.props.as, {}, this.props.children);
        this.setState({ ready: true });
      }
    
      render() {
        if (!this.state.ready) {
          return null;
        }
    
        return this.el;
      }
    }
    

    Usage:

    class App extends Component {
      render() {
        return <MyC as="span">Test</MyC>;
      }
    }
    

    Working example: https://codesandbox.io/s/xozpn8ol9o