loading...

Creating React Components - different syntaxes

chaituknag profile image Naga Chaitanya Konada ・1 min read

Intro

I would like to show the different ways we can create React Components. I like the arrow function statement style the most.

1 - Function declaration

// Different ways of creating react Components

// 1 - function declaration
import React from 'react'

function Component() {
  return <h1>Hello World</h1>
}

export default Component

2 - Anonymous function statement

// Different ways of creating react Components

// 2 - anonymous function statement
import React from 'react'

const Component = function() {
  return <h1>Hello World</h1>
}

export default Component

3 - Arrow function statement

// Different ways of creating react Components

// 3 - arrow function statement
import React from 'react'

const Component = () => {
  return <h1>Hello World</h1>
}

export default Component

4 - default export function

// Different ways of creating react Components

// 4 - export default function
import React from 'react'

export default () => {
  return <h1>Hello World</h1>
}

5 - classic component syntax

// Different ways of creating react Components

// 5 - classic component syntax
import React from 'react'

class Component extends React.Component {
  render() {
    return <h1>Hello World</h1>
  }
}

export default Component

What is your favorite one, is there a better one than the ones I mentioned here?

Posted on by:

chaituknag profile

Naga Chaitanya Konada

@chaituknag

FronteEnd enthu, with keen purpose to understand the big frameworks and stuff out there.

Discussion

markdown guide
 

I went from

5 - classic component syntax

1 - Function declaration

3 - Arrow function statement

4 - default export function

then back to 3 - Arrow function statement.

(I've never used 2 - Anonymous function statement).

The reason being that I learned React with Class components, and then hated this so moved toward using functions (especially w/ introduction of hooks).

I then moved onto default export, which I found it easy to declare w/o having to worry about how to name the component.

But then, I have a mouse-jerk problem, so sometimes move files around by mistake. With default export, I have to "read" what the component did, to be able to move it back to where it was.

When you name a function, and export it that way, you know what the component is w/o a second thought.

So my preference nowadays is the 4th one.

 

Very good.

I think one more reason why export default function approach might not be preferred is when you write propTypes and defaultProps. Because these require the name of the function to assign those types.