Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to namespace es6 classes (for React components)

This is part ES6 question part React question. I'm trying to use namespaced components in React with ES6 classes and Babel. So I guess the real question is how to name space es6 classes so I can do what is explained here: https://facebook.github.io/react/docs/jsx-in-depth.html#namespaced-components

Since I get an unexpected token error:

class Headline extends Component { ... }  class Headline.Primary extends Component { ...               ^ 
like image 538
Ben Avatar asked Aug 26 '15 15:08

Ben


People also ask

How do you use ES6 to define a component in react?

Using an ES6 class to write the same component is a little different. Instead of using a method from the react library, we extend an ES6 class that the library defines, Component . constructor() is a special function in a JavaScript class. JavaScript invokes constructor() whenever an object is created via a class.

What is ES6 class in react?

ES6 introduced classes. A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class , and the properties are assigned inside a constructor() method.

What is namespace Reactjs?

In the context used in the link in OP, the "namespace" is an object, and properties are added to that object one by one using the dot notation for property access. You could replicate that by using a class expression instead: 'use strict' var ns = {} ns. MyClass = class { constructor() { console.

What class do we extend from to create a react component in ES6 syntax?

class Counter extends React. Component { constructor(props) { super(props); this.


1 Answers

The ECMAScript-6 class declaration syntax expects a standard BindingIdentifer as the class name. A dot is not a valid character inside an identifier name.

In the context used in the link in OP, the "namespace" is an object, and properties are added to that object one by one using the dot notation for property access.

You could replicate that by using a class expression instead:

'use strict'    var ns = {}    ns.MyClass = class {    constructor() {      console.log('in constructor')    }  }    new ns.MyClass()
like image 189
Amit Avatar answered Oct 03 '22 09:10

Amit