Tag Archive for: React

Create an universal React app

First of all read the whole post, secondly install Create React App globally and create an app using create-react-app my-app, then before any coding add packages to your app. As soon as you finish all package installations you can start coding using my basics code snippets if you need to 🙂

Add main React package to your enviroment

Create React App

npm i -g create-react-app

This will allow you to create React Apps with no build configuration anywhere in your computer.

create-react-app my-app

cd my-app/

npm start

This will create a React App called my-app pointing to http://localhost:3000/, any time you save your files your app will be updated automatically.

Link to the library.

Add packages to your React app

Within my-app folder.

Bootstrap

npm i -S bootstrap

npm i -S react-bootstrap

npm i -S react-router-bootstrap

This will allow us to use this front-end framework in a easier way (with React).

Links to the library.

For example lets code our home page (home.js)

import React from 'react';
import { Grid, Row, Col, Jumbotron, Image } from 'react-bootstrap';

import people from '../media/people.png';

function Home(props) {
  const t = props.t; // we will pass the translation function via props
  return (
    <div>
      <Grid>
        <Jumbotron>
          <h1>{t('Open knowledges')}</h1>
          <p>Cool text right here</p>
        </Jumbotron>
      </Grid>

      <Grid>
        <Row>
          <Col lg={12}>
            <p>I love paragraphs.</p>
            <p>I love paragraphs.</p>
          </Col>
        </Row>
        <Row>
          <Col lg={12}>
            <p>I love paragraphs.</p>
            <Image className="detached" src={people} responsive />
          </Col>
        </Row>
      </Grid>
    </div>
  );
}

export default Home;

Anything that you would use repeatedly in other pages of your website should be in a different file (component), such as the navigation bar and the footer. Create a layout component to organize your components all together (layout.js)

import React, { Component } from 'react';

import Navigation from '../components/Navigation';
import Footer from '../components/Footer';

class Layout extends Component {
  render() {
    return (
      <div>
        <Navigation t={this.props.t}></Navigation>
        {this.props.children}
        <Footer></Footer>
      </div>
    );
  }
}

export default Layout;

React Router

npm i -S react-router

npm i -S react-router-dom

This will make our website’s routing easier.

Link to the library.

Let’s create our website/app (index.js) with two pages, for example Home (home.js) and About (about.js)

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';

import './index.css';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';

import Layout from './pages/Layout';
import Home from './pages/Home';
import About from './pages/About';
import i18n from './i18n';

let t = i18n.t.bind(i18n); // for translations

ReactDOM.render(
  <BrowserRouter>
    <div>
      <Route exact path="/" render={() => <Layout t={t}><Home t={t} /></Layout>} />
      <Route exact path="/about" render={() => <Layout t={t}><About t={t} /></Layout>} />
    </div>
  </BrowserRouter>,
  document.getElementById('root')
);

Add i18next package

npm i -S i18next

This will let us do our website/app internationalization.

Link to the library.

import i18n from 'i18next';

i18n
  .init({
    fallbackLng: 'en',
    lng: navigator.language.split('-')[0],
    debug: true,
    resources: {
      en: {
        translation: {
          "Hello": "Hola",
          "Bye": "Adiós"
        }
      }
    }
  });

export default i18n;

Futher details using i18n in this post: Create a multilingual React website.

How your files structure would look like?

.
+-- _components
|   +-- Footer.css
|   +-- Footer.js
|   +-- Navigation.css
|   +-- Navigation.js
+-- _media
|   +-- logo.svg
+-- _pages
|   +-- Layout.js
|   +-- Home.js
|   +-- About.js
+-- i18n.js
+-- index.css
+-- index.js

 

Create a multilingual React website

First of all create a react app ready to go

create-react-app MY-WEBSITE

This will create a react app with everything configured.

npm start

Add i18next package

npm i -S i18next

This will let us do our website/app internationalization.

Set up your I18next file

Create a i18n.js file in the src folder with this code:

import i18n from 'i18next';

i18n
  .init({
    fallbackLng: 'en',
    lng: navigator.language.split('-')[0],
    debug: true,
    resources: {
      en: {
        translation: {
          "Hola": "Hello",
          "Adiós": "Bye"
        }
      }
    }
  });

export default i18n;

Finally, indicate which text you want to translate

Import your i18n.js and use its t function to indicate where it should be the internationalization.

import React, { Component } from 'react';
import logo from './logo.svg';
import i18n from './i18n';
import './App.css';

let t = i18n.t.bind(i18n);

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>{t("Hola")}</h2>
        </div>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

 

React Setup

How to deal with the React Setup fatigue? I have seen many tutorials out there, many of them complex and outdated, therefor I would like to bring you my best with a basic working setup.

First of all, I suppose that you know at least what is Node, NPM, React, Babel and Webpack, I know, I know, the headline is about React but we cannot use React as we use JavaScript directly in the browser, although React is JavaScript, it has extra things like JSX for example that can not be execute directly in the browser.

  • React is a JavaScript library to build user interfaces. It divides the code in components (button, dialog, etc) and keeps things update efficiently.
  • Babel is a compiler that makes compatible new JavaScript generations and extra things like JSX. So, as we said, because we cannot use directly React in the browser we need Babel to transform it into current JavaScript.
  • Webpack is a bundler that lets you organize your code. We can use it for many things but here we will use it for: connecting React with Babel, creating a development enviroment with an auto update server and creating an output file with everything ready for browsers.

Ok, that’s all, so, why do we need also Node and NPM? Everything is linked. You need to install them before continue with the setup.

  • NPM is a super power package manager that installs, publishes and manages node programs. We are going to install React, Babel and Webpack in our computer with NPM.
  • Node is JavaScript on the Server.

Don’t be panic, things look difficult when you don’t know anything about them at first, but as soon as we dive into them you will see that they are not (that much :P).

Setup

  1. Create a project folder (ex: reactapp), open it and create another folder for your app (ex: app), open it and create one more for React’s components (ex: components).
  2. Whitin the reactapp folder open a terminal/console and type:
    • npm init
  3. Leave all the npm init questions empty (we will come back later): click enter till you escape. This will create a package.json file about your app.
  4. Stay in the terminal and install(i) for your app(-S) react and react-dom:
    • npm i -S react react-dom
  5. Then, install for development(-D) babel:
    • npm i -D babel-core babel-loader babel-preset-react babel-preset-react-hmre
  6. To finish with the package installations install for development(-D) webpack:
    • npm i -D webpack webpack-dev-server html-webpack-plugin
  7. If you have any permission problem (EACCES) type sudo at the beggining of the command and if you need to change package.json permissions from root to your user use:
    • sudo chown user_name package.json
  8.  Now, create a file called .babelrc and write in it that we are going to use react presets:
    • { presets: [‘react’] }
  9. Open package.json and within “scripts”: {} write what we are going to use in production(build) and development(start) :
    • “build”: “webpack”,
    • “start”: “webpack-dev-server –progress –inline –hot”
  10. Finally, let’s configure webpack. Create a file called webpack.config.js and write in it:
const HTMLWebpackPlugin = require('html-webpack-plugin')
const HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
  template: './app/index.html'
})

module.exports = {
  entry: './app/index.js',
  output: {
    filename: 'transformed.js',
    path: './build'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      }
    ]
  },
  plugins: [HTMLWebpackPluginConfig]
}

So far, we have set up our environment, let’s test it.

Test

  • In your components folder, create a file called App.js with a basic component (ex: a stateless functional component):
const React = require('react')

function App() {
  return <h1>Yuhuu, It is working</h1>
}

module.exports = App
  • Within your app folder create a basic index.hml with a container for your app:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>React example</title>
</head>
<body>
  <div id="app"></div>
</body>
</html>
  • Create a basic index.js to render your React app:
const React = require('react')
const ReactDOM = require('react-dom')
const App = require('./components/App')

ReactDOM.render(
  <App />,
  document.getElementById('app')
)
  • Write in your terminal line (inside your project folder):
    • npm start
  • Open your browser at http://localhost:8080/

Welcome to React! Try to change our component and you will see how everything changes on the fly 🙂

  • For production use:
    • npm run build

Do you want to do it easy?

You have learned how to deal with React configuration from scratch. You spent a lot of time but not code for your app at all.

No configuration or complicated folder structures, just the files you need to build your app.

Create Apps with No Configuration: Welcome to Create React App!

Basic React example on JSFiddle

Basic React example to synchronize (write) text in an HTML heading tag while typing in an input tag.

Do not forget to set Babel on JSFiddle and add react.js and react-dom.js libraries.