Esben von Buchwald
Esben von Buchwald

Reputation: 3069

Use Generic flow types in React component Props and instantiate generic component>

I have a Flow generics vs React Components issue, which I haven't been able to find the answer to, on google.

I want to make a generic component with props that takes generic arguments, and instantiate that in a render() method. No luck so far - my minimal example code is here:

Try it out

import React from 'react'


// Different commands for different contexts
type PaymentCommands = 'pay' | 'reject' | 'unused'
type CartCommands = 'checkout' | 'empty'


type Command<CommandType> = {
  userId: string,
  command: CommandType,
}

// Props let the component take different types of commands
type Props<CommandType> = {
  commands: Command<CommandType>[]
}


// The CommandButtons component should be used for sending various commands depending on context.
class CommandButtons<CommandType> extends React.Component<Props<CommandType>> {
  render() {
    return (
      <div>
        BLABLA
      </div>
    )
  }
}

// But no luck in instantiating a specific type of the CommandButtons generic, so far
const PaymentCommandButtons = () =>  {return CommandButtons<PaymentCommands>}

type PaymentContainerProps = { userId: string }
class PaymentContainer extends React.Component<PaymentContainerProps> {
  render() {
//      return (
//          <div><CommandButtons<PaymentCommands> commands={[{userId: 1, commmand: 'pay'}, {userId:2, command: 'reject'}]} /></div>
//        )
    return (
       <div><PaymentCommandButtons commands={ [{userId: 1, commmand: 'pay'}, {userId:2, command: 'reject'}] } /></div>
    )
  }
}

Upvotes: 3

Views: 1367

Answers (1)

Esben von Buchwald
Esben von Buchwald

Reputation: 3069

I solved it like this!

const PaymentCommandButtons = (props: Props<PaymentCommands>) => <CommandButtons { ...props } />

Upvotes: 3

Related Questions