React - How to export a pure stateless component

JavascriptReactjsEcmascript 6Export

Javascript Problem Overview


How can I export a stateless pure dumb component?

If I use class this works:

import React, { Component } from 'react';

export default class Header extends Component {
	render(){
		return <pre>Header</pre>
	}
}

However if I use a pure function I cannot get it to work.

import React, { Component } from 'react';
export default const Header = () => {
	return <pre>Header</pre>
}

Am I missing something basic?

Javascript Solutions


Solution 1 - Javascript

ES6 doesn't allow export default const. You must declare the constant first then export it:

const Header = () => {
  return <pre>Header</pre>
};
export default Header;

This constraint exists to avoid writting export default a, b, c; that is forbidden: only one variable can be exported as default

Solution 2 - Javascript

Just as a side note. You could technically export default without declaring a variable first.

export default () => (
  <pre>Header</pre>
)

Solution 3 - Javascript

you can do it in two ways

const ComponentA = props => {
  return <div>{props.header}</div>;
};

export default ComponentA;

export const ComponentA = props => {
  return <div>{props.header}</div>;
};

if we use default to export then we import like this

import ComponentA from '../shared/componentA'

if we don't use default to export then we import like this

import { ComponentA } from '../shared/componentA'

Solution 4 - Javascript

You can also use a function declaration instead of assignment:

export default function Header() {
    return <pre>Header</pre>
}

In your example, you already use curly brackets and return so this is apparently matching with your needs with no compromise.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser6002037View Question on Stackoverflow
Solution 1 - JavascriptDamien LerouxView Answer on Stackoverflow
Solution 2 - JavascriptcheersjoshView Answer on Stackoverflow
Solution 3 - Javascriptsravan ganjiView Answer on Stackoverflow
Solution 4 - JavascriptCristianView Answer on Stackoverflow