Build React Apps | Getting Started With Flux (Intro) 04

Video Tutorial

Getting Started

Flux is a technique for Making React Components more flexible and event-based state altering, where you can submit an event on a child component then send a specific data depending on the component’s state to the main App Component in order to use data in mutiple components also it easly allows you to store your app state in a store so you can refer to it or access it at any time during the rendering process, for the event system we are going to use nodejs events system for emitting and adding listeners for the events you can use any framework, library that allows you to use an event driven system.

One another is there is a Flux module from npm that you can use, it uses the same structure as we are going to work with but it does handle the store and state altering in a bit different way (Much more Like Redux Does), so understanding this tutorial will easily allow you to change into other frameworks.

Now we are going to create a new Component that we will use to make the flux architecture works for us, so we are going to create a loginBox component where it will allow us to enter username and password then send it to the main component so we can then render it from there in to the DOM.

First, let’s initialize the LoginBox component

//New Component
class LoginBox extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return null;
  }
}

Let’s create the Username and password inputs

...
//Under the Render Method 
render() {
    return <div>
        <label>Enter your Username</label>
        <input type="text" className="form-control" placeholder="Enter Username" ref={input => (this.usernameInput = input)} />
        <label>Enter your Password</label>
        <input type="password" className="form-control" placeholder="Enter Password" ref={input => (this.passInput = input)} />
        <button type="button" className="btn btn-success" onClick={this.onSubmit.bind(this)}>
          Submit
        </button>
      </div>;
}
...

here there are two things that I need to mention. First, the ref attribute under the input element let you store the DOM element under your class so later on your code you can easily reference it and get the data out from it, it takes a callback and the current element as an argument so you can assign it to your class, also we add a listener for the button click event in order to know that the button has been submitted then we can grab the data and emit the event

//Add it on your LoginBox Class 
...
onSubmit(e) {
  console.log(this.usernameInput.value, this.passInput.value);
}
...

Make sure to render the LoginBox Component under the Header Component (Which is the Main Component) in order to get rendered to the DOM.

Ask you can see now whenever we type the username and password and submit them we get the logged to the console, but this is not what we want actually we need to send the username and password to the main Component (Header) and then we render them from there, you still can render the data on the LoginBox but for the seek of this tutorial and learning Flux we are going to take this to the next level in order to see how actually works with Flux.

So Flux actually is based on a Store, action dispatch architecture in another word: you have a store that holds your app state (for ex: username and password) and let’s say that you want to change the username at some point so you dispatch an action to the store depending on the dispatched action the store respond to your request and change the state for you, and in this process we are going to use event-based system (Nodejs Events) in order to make everything clear and easy to understand.

First, we need to install a development server and we are going to use Webpack-Dev-Server so we can use nodejs modules (Events Module) in the Front-End (React Rendering Process) so make sure to install this

npm install webpack-dev-server@1.14.1
# Well we use this version because the latest Webpack 4 version gives us an Error
# Feel Free to use the Latest Version.

Also, we need to configure our dev environment, so under the package.json change the watch script to

//package.json
...
"scripts": {
   "watch": "cross-env NODE_ENV=development webpack-dev-server --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
}
...
//Notice that we are using webpack-dev-server instead of webpack

also the laravelMix-webpack config file

//Change target from node into web 
...
mix.webpackConfig(
    (module.exports = {
        target: "web",
        ...

Now we are ready to go, you can start the server by typing

npm run watch

You should see a server start with a specific URL and a Port make sure to use it in order to access your app

Now the working environment is set up and ready to go.

Start Using Flux 

We need to create the Flux store for linking the components together with the help of the nodejs EventEmitter for event dispatching

import { EventEmitter } from "events";
//Flux Store
class Store extends EventEmitter {
  init(username, password) {
      this.emit('data-received', username, password);
  }
}
//We extends it from the Event Emitter Class for us to be able to emit/listen to events 
//Also Initialize the Store (Make Sure to do it before initializing other Components)
let store = new Store();

So we create a Store class and extends from the EventEmitter, inside the class we create an init method that takes the username and password then emits an event named (‘data-received’) passing in the received username and password, so if you can propely guess that the init method needs to be called in the LoginBox once the button is pressed (Submitted) in order to dispatch an event holds the needed data, and the Header (Main Component) listen for that event, whenever it gets submitted then the Header can render the received data (Username and Password) So let’s implement it.

Under the LoginBox onSubmit method init the store

...
onSubmit() {
   store.init(this.usernameInput.value, this.passInput);
}
...

Now let’s listen to the event in the Header

...
componentWillMount() {
   //We use the on Method to listend for events, it takes a callback with the passed arguments 
   store.on("data-received", (username, password) => {
      this.setState({username: username, password: password});
   });
}
//Also we update our state by setting the username and password so we can render them 
...

We use the ComponentWillMount method because it is the best place to register event listeners (when our component is ready to get rendered) then whenever the event is triggered (emitted) we run the callback so we can get the username and password also updating the state will allow us to update the component and render the newly received data.

You can render the data under the Header Component

...
render() {
   return (
       ...
        <div>
          <h3>Your Username and Password are : </h3>
          <br />
          <h5>{this.state.username + "  " + this.state.password}</h5>
        </div>
        <LoginBox />
   );
}
...

And this is it, now you can try to access your dev server and type your username and password, and they should get rendered respectively in the Header Component, and that should represent the Connection between two or more component does matter (a parent or a child component).

What’s Next

So After taking a closer look on how Flux and React can work together in order to achieve a great workflow and data management using events driven system, So in the next video tutorials we will try to create an advanced example using Flux and React in order to see how apps actually get created, Stay Tunned!

No Comments Yet