Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly store React components in separate files and import React?

I've completed a few intro to React tutorials and am trying to put some of my knowledge so far to use. I've successfully created some components inside of a <script type='text/babel'> and using babel's browser.js to convert this to JS client-side in the browser.

However, I'm now trying to break out my components into individual files, transpile them, and then serve the transpiled JS to the client rather than have that transpilation done client-side.

I'm confused on how to properly import ReactJS into my component JSX files. I haven't built large JS applications before, so I'm not familiar with the ways to import libraries into other modules.

Here's one of my component JSX files:

var SidebarFilter = React.createClass({
  render: function() {
    return (
        <div className="btn-group">
          Some markup removed for brevity. 
        </div>
    );
  }
});

In my main html file, if I have:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>

Prior to any of my <script> tags for my components, everything works fine. But if the components are placed above the react/reactdom script tags, it doesn't work.

I've seen javascript has an import and there is also require, but I'm not sure what the differences are, which is better to use when, and if either/both require any additional building or if they're used right in the browser.

Thanks!

like image 617
Joseph Avatar asked Dec 08 '22 23:12

Joseph


1 Answers

If you are just learning react then your way of doing using script tag is inside html fine.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>

If you want to develop an application which can be deployed to production you need to follow following steps. No doubt there are much better tutorial available over the internet but it will give you some idea.

1.Need Browserfiy or Webpack:

In browsers you can not require or import modules as you usually do while writing node.js code. With the help of Browserify/Webpack you can write code that uses require/import in the same way that you would use it in node environment. I am assuming you will use webpack considering its popularity.

2. Install dependencies (es6)

These are minimal dependencies you need in your project (package.json) to get it working

  "devDependencies": {
        "babel-cli": "^6.3.17",
        "babel-core": "^6.3.21",
        "babel-eslint": "^5.0.0-beta6",
        "babel-loader": "^6.2.0",
        "babel-preset-es2015": "^6.3.13",
        "babel-preset-react": "^6.3.13",
        "babel-preset-stage-3": "^6.3.13",
        "css-loader": "^0.23.0",
        "eslint": "^1.10.3",
        "eslint-loader": "^1.1.1",
        "eslint-plugin-react": "^3.12.0",
        "style-loader": "^0.13.0",
        "webpack": "^1.12.9",
        "webpack-dev-server": "^1.14.0"
      },
      "dependencies": {
        "react": "^15.0.0-rc.1",
    "react-dom": "^15.0.0-rc.1"

3.Write your webpack-config.js file

A sample webpack config file should like this. Don't ask me about each bit of it but rather have a look on webpack tutorial because I can not explain everything here. Just remember the fact that Webpack is a module bundler that bundles javascript and other assets for the browser.

var path    = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'source-map',
  entry: {
    main: [
      'webpack-dev-server/client?http://localhost:8080',
      'webpack/hot/only-dev-server',
      './src/index.js'
    ]
  },
  output: {
    path: path.join(__dirname, 'public'),
    publicPath: 'http://localhost:8080/public/',
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
   loaders: [
      {
        test      : /\.jsx?$/,
        include   : path.join(__dirname, 'src'),
        loader    : 'react-hot!babel'
      },
      {
        test      : /\.scss$/,
        include   : path.join(__dirname, 'sass'),
        loaders   : ["style", "css?sourceMap", "sass?sourceMap"]
      },
      {
          test    : /\.(png|jpg|svg)$/,
          include : path.join(__dirname, 'img'),
          loader  : 'url-loader?limit=30000&name=images/[name].[ext]'
     } // inline base64 URLs for <=30k images, direct URLs for the rest
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

4.Set up entry point and routes for your application

src->index.js src->routes.js

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Router,browserHistory} from 'react-router';
import routes from './routes';

ReactDOM.render(
    <Router routes={routes} history={browserHistory}/>
  , document.querySelector('.init')
);

routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/app';
import Home from './components/home';


module.exports = (
       <Route path="/" component={App}>
           <IndexRoute component={Home}/>
       </Route>
)

5.Setup index.html in your project root

<!DOCTYPE html>
<html>
  <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Welcome to ReactJs</title>
  </head>
  <body>
    <div class="init"></div>
  </body>
  <script src="./public/bundle.js"></script>
</html>

6.Running

Form your project root type

webpack-dev-server --progress --colors

import and require

import and require are very similar in functionality. Only difference is that import is new syntactic sugar available with es6 while require is used with es5.

like image 66
WitVault Avatar answered May 12 '23 11:05

WitVault