Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot export const arrow function

Tags:

ecmascript-6

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?

like image 677
Nik So Avatar asked Jan 08 '16 12:01

Nik So


People also ask

Can you export an arrow function?

To export arrow functions in JavaScript, we can use export directly with arrow functions. const hello = () => console. log("hello"); export default hello; to export the hello function as a default export with export default .

Can you export a const?

Use named exports to export constants in JavaScript, e.g. export const A = 'a' and export const B = 'b' . The exported constants can be imported by using a named import as import {A, B} from './another-file. js' . You can have as many named exports as necessary in a file.

Can we default export Arrow function in JS?

You cannot name a default export.

How do you export constant in React?

To import a constant from another file in React: Export the constant from file A , e.g. export const str = 'First' . Import the constant in file B as import {str} from './another-file' .


1 Answers

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

like image 190
Henrik Andersson Avatar answered Oct 04 '22 23:10

Henrik Andersson