tatsu
tatsu

Reputation: 2536

concise and readable syntax for props in a react component in typescript

So if you declare a React.FC , then you get to do a type declaration and thus get to pass it props :

const FuntionalComponent: React.FC<personType> = ({ id, nationality, name, familyName, age, selected }) =>

    <div>
       ...directly html
    </div>

export default FuntionalComponent;

But you cannot declare any methods or use hooks there (I have not found a way)

Then there's the React.Component type :

class Component extends React.Component<{}, {Stateproperty: string}>{

  constructor(){
  }

  hook(){
  }

  method(){
  }

  render() {
    return (
      <div>
         ...html finally
      </div>
    )
  }
}

export default component;

as you can see I can pass a state but not a props.

If I try something like this :

class Component extends React.Component<{propsProperty: Array}, {Stateproperty: string}>{

and then add my propsProperty to my html :

<Component propsProperty={thisArray} />

Yet, they error out with the following entry:

TS2322: Type '{ propsProperty: any; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.   Property 'tankData' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.

These tutorials seem to indicate that there is no other way to declare components:

https://riptutorial.com/reactjs/example/25321/declare-default-props-and-proptypes https://medium.com/@cristi.nord/props-and-how-to-pass-props-to-components-in-react-part-1-b4c257381654

I found this article about TypeScript errors in React: https://medium.com/innovation-and-technology/deciphering-typescripts-react-errors-8704cc9ef402, but it didn't have my issue.

I also tried this solution : https://stackoverflow.com/a/47395464/4770754. Even though it's clearly not the same issue, it seemed somewhat close, yet it didn't help.

React docs are not helpful since they ignore TypeScript and are not human-readable.

I need a way that's both concise, respects TypeScript and allows for both props and methods within the class body. Does this not exist at all?

Upvotes: 1

Views: 219

Answers (1)

gqstav
gqstav

Reputation: 2082

But you cannot declare any methods or use hooks there (I have not found a way)

A good standard way of declaring a FC is:

type ComponentProps = {
  id: string, 
  nationality: string, 
  ...
}

const MyComponent: React.FC<ComponentProps> = ({
  id, 
  nationality, 
  ...rest
  }: ComponentProps) => {
  
  const someMethod = () => {
    console.log('I am console logging');
  }


  return(
    <div>
      {/* HERE YOU WILL RENDER STUFF */}
    </div>
  )
}

Note that in the above I deconstruct the props on instantiation so that id, nationality can be leveraged directly in the component.

I don't think you need to worry too much about the syntax highlighting until you're familiar with the above.

Upvotes: 2

Related Questions