loading...
Cover image for Latest React Component Syntax, May 2020

Latest React Component Syntax, May 2020

ngduc profile image Duc Ng Updated on ・1 min read

It's May 2020, I just want to document the latest React Component Syntax so far.

Latest React version is v16.13.1, released in March 2020.

Engineers who are new to React often got confused about different syntax when reading through many tutorials and documents on the Internet. I hope this helps to clarify the recommended way to write the latest React Component.

Functional Component with Typescript

import * as React from 'react'

export interface Item {
  title: string
  done: boolean
}
export interface Props {
  initialItems?: Item[]
}
export default function TodoList({ initialItems = [] }: Props): React.ReactElement {
  const [items, setItems] = React.useState<Item[]>(initialItems)

  const onClick = () => {
    setItems([...items, { title: 'Fetched Item', done: false }])
  }
  return (
    <>
      <ul>
        {items.map((item) => (
          <li>{item.title}</li>
        ))}
      </ul>
      <button onClick={onClick}>Fetch More</button>
    </>
  )
}

Functional Component - Arrow syntax

const MyComponent: React.FC<Props> = ({ value }) => <div>Syntax</div>

Class Syntax

interface Props {
  value: number
}
interface State {
  text: string
}
class MyComponent extends React.Component<Props, State> {
  static defaultProps: Props = {
    value: 0
  }
  state: State = { text: 'Example' }

  render() {
    return <div>Syntax {this.props.value} {this.state.text}</div>
  }
}

References:

Posted on by:

ngduc profile

Duc Ng

@ngduc

JS enthusiast / 17y tinkering with screens & code.

Discussion

markdown guide
 

A quick note: when initializing useState with some value, then it's redundant to add type definition. TS would automatically pick it from the default value.

so, the snippet
const [count, setCount] = React.useState<number>(0);

can be rewritten as:
const [count, setCount] = React.useState(0);

 

Not always true. If you initialise a value to null, TS then only allows null for the field.
Then we need to do this ->

const [data, setData] = 
useState<number | null>(null);
 

The comment wasn't for union types. It was an addition to the article from a purely linting perspective. Let's suppose you have a loader and you are using const [loading, setLoading] = useState<boolean>(false), in that case <boolean> is redundant here.

 

Right. The example just demonstrated how to put a type in, it will be helpful for custom types.

 

Always prefer types to interfaces in TS

 

There are some opinions about inheritance syntax. Interface's "extends" is more readable than type inheritance syntax.

 

I thought you were going to present some new component syntax