Building webViews with React

First of all, we will create a home view from which React will be called. So, let's create index.html, which has the following contents, in the template directory:

    <!DOCTYPE html> 
    <html> 
     <head lang="en"> 
      <meta charset="UTF-8"> 
      <title>Flask react</title> 
    </head> 
   <body> 
     <div class="container"> 
       <h1></h1> 
       <br> 
       <div id="react"></div> 
 
    </div> 
 
   <!-- scripts --> 
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/
react/15.1.0/react.min.js"></script> <script src="https://npmcdn.com/react-
[email protected]/umd/ReactRouter.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/
libs/react/15.1.0/react-dom.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/
react/0.13.3/JSXTransformer.js"></script> </body> </html>

As you can see in the preceding HTML page, we have defined id ="react", which we will use to call the React main function based on the ID, and perform a certain operation.

So, let's create our main.js, which will send a response, with the following code:

    import Tweet from "./components/Tweet"; 
    class Main extends React.Component{ 
    render(){ 
      return ( 
      <div> 
        <h1>Welcome to cloud-native-app!</h1> 
      </div> 
      ); 
    } 
   } 
 
 
   let documentReady =() =>{ 
    ReactDOM.render( 
    <Main />, 
     document.getElementById('react') 
    ); 
  }; 
  
  $(documentReady); 

Now we have defined our basic structure of the React response. Since we are building an application with multiple views, we need a build tool which will help us put all our assets, including JavaScript, images, fonts, and CSS, under one package, and generate it into a single file.

Webpack is the tool which will help us solve this problem.

Webpack should already be available, as we defined the Webpack package as part of package.json, which we installed earlier.

Webpack, basically, reads a single entry file, which could be the .js file, reads its child components, and then converts them into a single .js file.

Since we have already defined it in package.json, it is already installed.

In Webpack, we need to define a configuration which will help it to identify the entry file and the loader that is to be used to generate a single .js file. Also, you need to define the filename for the generated code.

Our Webpack configuration would be something like this:

    module.exports = { 
      entry: "./static/main.js", 
      output: { 
        path: __dirname + "/static/build/", 
        filename: "bundle.js" 
      }, 
     resolve: { 
       extensions: ['', '.js', '.jsx'] 
     }, 
     module: { 
        loaders: [ 
            { test: /.js$/, exclude: /node_modules/, loader: "babel-
loader", query:{presets:['react','es2015']} } ] } };

You can extend the preceding configuration based on your use cases. Sometimes, developers try *.html as the entry point. In that case, you need to make appropriate changes.

Let's move on to build our first webView using the following command:

$ webpack -d  

The -d attribute in the last command is used for debugging; it generates another file, bundle.js.map, which shows the activity of Webpack.

Since we are going to build the application repeatedly, we can use another flag, --watch or -w, which will keep track of the changes in the main.js file.

So, now our Webpack command should be something like the following:

$ webpack -d -w

Now we have built our application. Remember to change your routes in app.py so that home should be navigated as follows:

    @app.route('/index') 
    def index(): 
     return render_template('index.html') 

Let's check what our home page looks like now.

You can also check whether we have React and react-dom running in the background in the inspect mode.

This is a very basic structure to understand the workings of React. Let's move on to our use case, where we have created tweet webViews, and the user can view the old tweets as well.

So, let's create Tweet.js, which will have the basic structure of tweets, such as a textbox for contents, and a button to post tweets. Add the following code to Tweet.js:

    export default class Tweet extends React.Component { 
 
    render(){ 
     return( 
        <div className="row"> 
                </nav> 
        <form > 
          <div > 
            <textarea ref="tweetTextArea" /> 
            <label>How you doing?</label> 
              <button >Tweet now</button> 
          </div> 
         </form> 
        </div> 
        ); 
      } 
   } 

Let's call this function from main.js, so that it is loaded on the home page, by updating the render function as follows:

    import Tweet from "./components/Tweet"; 
    render(){ 
      return ( 
      <div> 
        <Tweet /> 
      </div> 
     ); 
    } 

If you load the page now, it will be pretty simple. Since we want to create a web application, which should be attractive, we will use a couple of CSS here to do so. In our case, we are using Materialize CSS (http://materializecss.com/getting-started.html).

Add the following block of code in index.html:

    <link rel="stylesheet"  
href="https://cdnjs.cloudflare.com/ajax/libs/
materialize/0.98.1/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/
materialize/0.98.1/js/materialize.min.js"></script> Also, we need to update Tweet.js as follows render(){ return( <div className="row"> <form > <div className="input-field"> <textarea ref="tweetTextArea" className="materialize-
textarea" /> <label>How you doing?</label> <button className="btn waves-effect waves-light
right">Tweet now <i className="material-icons
right">send</i></button> </div> </form> </div> ); }

Let's try to add tweets, and send them across with state so that some tweets should be shown.

In the Main class of main.js, add the following constructor function to initialize the state:

    constructor(props){ 
     super(props); 
     this.state =  { userId: cookie.load('session') }; 
     this.state={tweets:[{'id': 1, 'name': 'guest', 'body': '"Listen to 
your heart. It knows all things." - Paulo Coelho #Motivation' }]} }

Now update the render function as follows:

    render(){ 
      return ( 
      <div> 
         <TweetList tweets={this.state.tweets}/> 
      </div> 
      ); 
     } 
    } 

Let's create another file, TweetList.js, which will show the tweets, with the following code:

    export default class TweetList extends React.Component { 
     render(){ 
        return( 
        <div> 
          <ul className="collection"> 
           <li className="collection-item avatar"> 
           <i className="material-icons circle red">play_arrow</i> 
           <span className="title">{this.props.tweetedby}</span> 
          <p>{this.props.body}</p> 
          <p>{this.props.timestamp}</p> 
          </li> 
         </ul> 
        </div> 
       ); 
      } 
     } 

Great! Now we have added this template. Let's check out our home page and see how the CSS works there. But before that, since we are using Webpack for building, make sure you add the following line to load bundle.js every time--this will run the webViews in the index.html file.

    <script type="text/javascript" src="./static/build/bundle.js">
</script>

Awesome! The home page should look something like this:

Let's move forward to post tweets--we should be able to add new tweets, and they should be updated in TweetList.js as well.

Let's update our Tweet.js code so that it sends the tweets to main.js to process them. Now, we need to send our tweets to main.js, in order to do so , we need to update our Tweet.js file with the following code:

    sendTweet(event){ 
      event.preventDefault(); 
      this.props.sendTweet(this.refs.tweetTextArea.value); 
      this.refs.tweetTextArea.value = ''; 
     } 

Also, be sure to update the render function with the form onSubmit attribute as follows:

    <form onSubmit={this.sendTweet.bind(this)}> 

So, after adding content into the text area, it should submit the tweet as well.

Now, let's update the render function of main.js to add new tweets, as follows:

    <Tweet sendTweet={this.addTweet.bind(this)}/> 

We also need to add the addTweet function in the Main class, defined in the following:

    addTweet(tweet): 
     let newTweet = this.state.tweets; 
     newTweet.unshift({{'id': Date.now(), 'name': 'guest','body':
tweet}) this.setState({tweets: newTweet})

Your page, after adding the new tweet, should look something like this:

Currently, we are using React to hold the data in an array. Since we have built our microservices to hold this kind of data, we should integrate our webView with the backend services.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.120.161