Skip to content Skip to sidebar Skip to footer

Exporting Functions With Reactjs And Babel

I have a project using reactjs, which is transpiled by babel. I use the es2015 and react transforms in my .babelrc. I am currently refactoring and in my first pass I basically did

Solution 1:

It's the same as defining the function as a variable but just adding export to the front e.g. (using ES6 syntax)

exportconstrender = () => (
  // Some other JSX
);

or alternatively

exportvar render = function() {
  return (
    // Some other JSX
  );
};

Solution 2:

Exporting functions is no different than exporting class. Basic rules must be followed .

  1. Function/Class name should in CAPS
  2. There will be only one "export" line .
  3. Every function return body should have a single tag encompassing other parts. Most commonly used is a tag .
  4. This usually works: import App from "./App"; where App.js is my jsx file. You can do an explicit import too . : import AllApp from "./classhouse.jsx";
  5. Name of the js/jsx file does not matter. It can be anycase (lower, upper).
  6. For returning multiple functions from one file, you need to create one more function , that encompasses all other functions .

See the example below showing multiple functions returned.

importReactfrom'react';

/* All function / class names HAS TO BE in CAPS */varApp1 = function (){
    return (
        <div><h1>
                Hello World
            </h1></div>
        )
}

varApp2 = function (){
    return (
        <div><h1>World Number 2 </h1></div>
           );
}

varAllApp = function (){
    return (
        <div><App1 /><App2 /></div>
        );
}

exportdefaultAllApp;

My index.js file:

importReactfrom'react';
importReactDOM from"react-dom";
importAllAppfrom"./classhouse.jsx"; /* Note: App name has to be in CAPS */importAppfrom"./App";

const jsx =
<div><AllApp /><App /></div>ReactDOM.render(jsx, document.getElementById("root"));

Solution 3:

You are writing functional components in wrong way.

functionWelcome() {
  return<h1>Hello World</h1>;
}

or

constWelcome = () => {
    return<p>Hello Wrold</p>
}
exportdefaultWelcome ;

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

Post a Comment for "Exporting Functions With Reactjs And Babel"