Wednesday, August 3, 2016

Using JSX and React_part 1


JSX is similar to a mix of XML and HTML. You use JSX within React code to easily create components for your apps. JSX transforms into JavaScript when React compiles the code.

The beauty of React is that you can create reusable code and easily structure your app from a component-based mindset. Finally, the gap between mocking up wireframes of semantically formed ideas and implementing them has never been closer.

Your First Taste of JSX

Here is an example of JSX being used to render HTML:

  1. var div = <div className="foo" />;
  2. ReactDOM.render(div, document.getElementById('example'));

To create a component, just use a local variable that starts with an upper-case letter, e.g.:

  1. var MyComponent = React.createClass({/*...*/});
  2. var myElement = <MyComponent someProperty={true} />;
  3.  
  4. ReactDOM.render(myElement, document.getElementById('example'));

Note: There are reserved words in JSX, as it is essentially JavaScript after all—so keywords such as class and for are discouraged as attribute names. Instead, React components expect the React property names such as className and htmlFor, for example.

Nesting Tags
Specify children inside your JSX as so:

  1. var User, Profile;
  2.  
  3. // You write in JSX:
  4. var app = <User className="vip-user"><Profile>click </Profile></User>;
  5.  
  6. // What will get outputted in JS:
  7. var app = React.createElement(
  8.   User,
  9.   {className:"vip-user"},
  10.   React.createElement(Profile, null, "click")
  11. );

Testing JSX

Use the Babel REPL to test out JSX.

Sub-Components and Namespaces

Form creation is easy with JSX and sub-components, for example:

  1. var Form = FormComponent;
  2.  
  3. var App = (
  4.   <Form>
  5.     <Form.Row>
  6.       <Form.Label htmlFor='login' />
  7.       <Form.Input name='login' type='text' />
  8.     </Form.Row>
  9.     <Form.Row>
  10.       <Form.Label htmlFor='password'  />
  11.       <Form.Input name='pass' type='password' />
  12.     </Form.Row>
  13.   </Form>
  14. );

To make this work, you must create the sub-components as attributes of the main component:

  1. var FormComponent = React.createClass({ ... });
  2.  
  3. FormComponent.Row = React.createClass({ ... });
  4. FormComponent.Label = React.createClass({ ... });
  5. FormComponent.Input = React.createClass({ ... });
Expressions

To use some JavaScript to create a result for use in an attribute value, React just needs you to wrap it in {} curly braces like so:

  1. // You write in JSX:
  2. var myUser = <User username={window.signedIn ? window.username : ''} />;
  3.  
  4. // Will become this in JS:
  5. var myUser = React.createElement(
  6.   User,
  7.   {username: window.signedIn ? window.username : ''}
  8. );

You can also just pass a boolean value for form attributes such as disabled, checked and so on. These values can also be hardcoded if you like by just writing plain HTML.

  1. // Make field required
  2. <input type="text" name="username" required />; 
  3. <input type="text" name="username" required={true} />;
  4.  
  5. // Check by default
  6. <input type="checkbox" name="rememberMe" value="true" checked={true} />;
  7.  
  8. // Enable a field
  9. <input type="text" name="captcha" disabled={false} />
  10. Spread Attributes

When you want to set multiple attributes, ensure you do this on declaration of your component and never after. Later declaration becomes a dangerous anti-pattern that means you could possibly not have the property data until much later in execution.

Add multiple properties to your component as so, using ES6’s new ... spread operator.

  1. var props = {};
  2.  props.username = username;
  3.  props.email = email;
  4.  var userLogin = <userLogin {...props} />;
  5.  ```
  6.   
  7. You can use these prop variables multiple times. If you need to override one of the properties, it can be done by appending it to the component after the `...` spread operator, for example:
  8.  
  9.  
  10. ```js
  11. var props = { username: 'jimmyRiddle' };
  12. var userLogin = <userLogin {...props} username={'mickeyFinn'} />;
  13. console.log(component.props.username); // 'mickeyFinn'

Comments in JSX

You can use both the // and /* ... */ multi-line style comments inside your JSX. For example:

  1. var components = (
  2.   <Navigation>
  3.     {/* child comment, put {} around */}
  4.     <User
  5.       /* multi
  6.          line
  7.          comment here */
  8.       name={window.isLoggedIn ? window.name : ''} // Here is a end of line comment
  9.     />
  10.   </Navigation>
  11. );

Common Pitfalls With JSX

There are a few things that can confuse some people with JSX, for example when adding attributes to native HTML elements that do not exist in the HTML specification.

React will not render any attributes on native HTML elements that are not in the spec unless you add a data- prefix like so:

  1. <div data-custom-attribute="bar" />

Also, the rendering of HTML within dynamic content can get confusing due to escaping and the XSS protection that React has built in. For this reason, React provides the dangerouslySetInnerHTML.

  1. <div dangerouslySetInnerHTML={{__html: 'Top level &raquo; Child'}} />

An Example Chat Application

You may have seen the app Gitter. It’s a real-time web chat application that’s mainly aimed at developers. Many people are using it to discuss their projects on GitHub, due to its easy integration with GitHub and being able to create a channel for your repository.

This type of application can easily be created with React by implementing the WebRTC API to create a p2p chat in the browser. For this we will be using the PeerJs and socket.io modules for Node.

To give you a clear idea of the architecture of the application, here is a basic low-level UML diagram:


ChatServer receives signal messages with PeerJS, and each client will use it as a proxy for taking care of the NAT traversal.

We will start the app from the ground up to give you a good feel of how to create a React application. First create a new directory for your application, and inside it make a package.json.

  1. {
  2.   "name": "react-webrtc-chat",
  3.   "version": "0.0.0",
  4.   "description": "React WebRTC chat with Socket.io, BootStrap and PeerJS",
  5.   "main": "app.js",
  6.   "scripts": {
  7.     "start-app": "node app.js",
  8.     "start": "npm run start-app"
  9.   },
  10.   "keywords": [
  11.     "webrtc",
  12.     "react"
  13.   ],
  14.  "license": "MIT",
  15.   "dependencies": {
  16.     "express": "~4.13.3",
  17.     "peer": "~0.2.8",
  18.     "react": "~0.12.2",
  19.     "react-dom": "^0.14.1",
  20.     "socket.io": "~1.0.6"
  21.   },
  22.   "devDependencies": {
  23.     "babel-preset-react": "^6.0.14",
  24.     "babelify": "^7.1.0",
  25.     "browserify": "^12.0.1"
  26.   }
  27. }

This package.json file is used by npm in order to easily configure your application. We specify our dependencies: express, a web framework that we will use to serve our app; peer, the peerjs server we will use for signalling; socket.io which will be used for polling and the webRTC implementation. react-bootstrap and bootstrap are packages for using Twitter’s CSS framework to style our app.
Written by: Tom Whitbread

If you found this post interesting, please follow and support us.
Suggest for you:

Modern React with Redux

Build Apps with React Native

Meteor and React for Realtime Apps

Build Web Apps with React JS and Flux

The Complete Web Development Tutorial Using React and Redux




1 comment:

  1. Good blog on React JSX. All the code samples working fine. each concept is simple and clear in understanding, keep writing more useful posts like this.

    Best Regards,
    ReactJS Online Training Institute in Hyderabad, India

    ReplyDelete