Nik So
Nik So

Reputation: 16821

cannot export const arrow function

new to ES6, I was trying to make a React simple functional component like this

// ./Todo.jsx

    export default const Todo = ({
      todos,
      onTodoClick,
    }) => (
      <ul>
        {todos.map( (todo, i) =>
          <li key     = {i} 
              onClick = {() => onTodoClick(i) } 
              style   = {{textDecoration: todo.completed ? 'line-through': 'none' }}
              >
            {todo.text}
          </li>
        )}
      </ul>
    )

But

// Another file 
import Todo from './Todos.jsx';
console.log(Todo) // undefined

did not yield the arrow function.

but if I leave off the "const todo =" part in the export link, like so

    export default ({
      todos,
      onTodoClick,
    }) => (...)

It gets successfully imported.

Why is that?

Upvotes: 88

Views: 87115

Answers (2)

Afroz Quraishi
Afroz Quraishi

Reputation: 159

Arrow function default export:

import React from 'react';
const Body=()=>(
    <div>This is my body</div>
);
export default Body;

Arrow function Named exports:

  1. First Way
import React from 'react';

export const Body = () => (
    <div>This is my body</div>
);
  1. Second Way
import React from 'react';

const Body = () => {
    return <div>This is my body</div>
};

export {Body};

You can also use 1 default and multiple named exports in the same file check below examples:

Example 1:

import React from 'react';

const Body1 = () => {
    return <div>This is my body1</div>
};

const Body2 = () => {
    return <div>This is my body2</div>
};

export {Body1, Body2};
you can import by using below code.
import {Body1, Body2} from 'bodyComponentPath';

Example 2

import React from 'react';
const MainBody = () => {
    return <div>This is my MainBody</div>
};

const Body1 = () => {
    return <div>This is my body1</div>
};

const Body2 = () => {
    return <div>This is my body2</div>
};

export {Body1, Body2};
export default MainBody;
you can import by using below code.
import MainBody, {Body1, Body2} from 'bodyComponentPath';

/* use named export components inside the curly bracket only */

import MainBody, {Body1, Body2} from 'bodyComponentPath';

Upvotes: 13

Henrik Andersson
Henrik Andersson

Reputation: 47182

You're trying to export a default and declare a variable at the same time, which is invalid syntax.

Consider the following, since we know that you can declare multiple variables using only one instance of the keyword, var a, b, c; the export definition wouldn't make sense at all.

export default var a, b, c;

What would that mean? What would get exported?

Furthermore, using the export default syntax already creates a variable called default that needs to contain a value or reference.

Export the variable instead if you want to make it a constant.

const Todo = () => {};

export default Todo;

There is a thread about this on ESDiscuss

Upvotes: 147

Related Questions