Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain this abbreviated ES6 JSX declaration

An example in the SurviveJS handbook in the chapter on React and Webpack has me confused.

In Note.jsx:

import React from 'react';

export default () => <div>Learn Webpack</div>;

This deviates in a number of ways from what appears to be the standard way of declaring React components using JSX:

import React from 'react';
class Note extends React.Component {
  render() {
    return <div>Learn Webpack</div>;
  }
}

How does the first example work?

  1. How does it know the component is called Note so that it can be referred to as <Note/> in some parent component? Simply by filename match (removing the .jsx part?)
  2. Where's the render() function? And how is it possible to omit it?
  3. What are the limitations of this approach? I am guessing that it only works for wrapping a very simple rendered output, just mapping properties into some HTML...
  4. Where is this style documented? I can't seem to find any official documentation
like image 675
Tom Auger Avatar asked Dec 03 '25 22:12

Tom Auger


1 Answers

  1. It doesn't, when you do <Note /> that is just looking for a variable named Note in the local scope. When the component is imported into another file, you can name it whatever you want. e.g. import Note from './Note'; would import the default-exported function in your example.

  2. This is a stateless function component, https://facebook.github.io/react/docs/reusable-components.html#stateless-functions, as you linked to yourself. The function itself is the render, it has no class instance.

  3. They can store no state since they just take inputs and render outputs.

  4. Your specific example is just an arrow function. The documentation linked above uses standard non-arrow functions, but they are essentially interchangable in this case. e.g.

    export default () => <div>Learn Webpack</div>;
    

    is the same as

    export default function(){
      return <div>Learn Webpack</div>;
    }
    
like image 63
loganfsmyth Avatar answered Dec 05 '25 22:12

loganfsmyth