paulosullivan22
paulosullivan22

Reputation: 330

Typescript & React: Passing props between components vs default props

I am fairly new to Typescript and creating a React app with Typescript. I'm having a bit of trouble passing props from one component to another. I've included an example below, my issue is around default props for components.

When I call my child component in my parent component, I get an error:

Type '{}' is missing the following properties from type 'IProps': className, disabled ts(2739)

I thought that because I have default props on my child component, they would fill in for any missing props when calling the component from other components.

I know I can make individual props optional in the interface IProps in my child component using className?: string but this is not a solution I'm looking for as it presents more problems than it solves.

I'd prefer not to have to note each default prop when I call a child from another component like below as for some components, I have many props: <Child class={''} disabled={false} />

I'm sure there's a fairly simple solution for this but I can't find any direction so far. Any advice or direction would be welcome.

// Parent component: 

import React, { FC } from 'react'

import Child from './child'

const Parent: FC = () => {
    return (
        <Child />
    )
}

export default Parent


// Child component: 

import React, { FC } from 'react'

interface IProps {
  className: string
  disabled: boolean
}

const Child: FC<IProps> = ({ className, disabled }: IProps) => {
  return (
    <button className={className} disabled={disabled}>
      Click here
    </button>
  )
}

Child.defaultProps = {
  className: '',
  disabled: false,
}

export default Child

Upvotes: 8

Views: 28066

Answers (3)

Shrishail Uttagi
Shrishail Uttagi

Reputation: 436

You did right but missed to pass className and disabled props the child component.

const Parent: FC = () => { return ( ) }

Upvotes: -3

paulosullivan22
paulosullivan22

Reputation: 330

Solved it, for anyone looking at this answer: just need to pass in the default props into the component as well as any props as per code below:

import React, { FC } from 'react'

interface IProps {
  className: string
  disabled: boolean
}

const Child: FC<IProps & Child.defaultProps> = ({ className, disabled }: IProps) => {
  return (
    <button className={className} disabled={disabled}>
      Click here
    </button>
  )
}

Child.defaultProps = {
  className: '',
  disabled: false,
}

Upvotes: 8

rrd
rrd

Reputation: 5957

You can provide default arguments to stop this happening:

const Child: FC<IProps> = ({ className = 'foo', disabled = false }: IProps) => {
  ...
}

This should actually get around the optional props problem you have, especially if you use these default arguments (i.e., lazy devs not checking what props are required/optional). Now you can make them optional ...

Upvotes: 0

Related Questions