React Example + Bootstrap

45
1 / 45 Looking at the Codes React Examples Eueung Mulyana https://eueung.github.io/112016/react-exp CodeLabs | Attribution-ShareAlike CC BY-SA

Transcript of React Example + Bootstrap

Page 1: React Example + Bootstrap

1 / 45

Looking at the Codes

React ExamplesEueung Mulyana

https://eueung.github.io/112016/react-expCodeLabs | Attribution-ShareAlike CC BY-SA

Page 2: React Example + Bootstrap

React Version: 15.4.1Part 1 - Basic Examples: https://eueung.github.io/112016/react-cont

Introduction to React already covered here: https://eueung.github.io/112016/react

2 / 45

Page 3: React Example + Bootstrap

Outline

Starter Kit - Cnt'd

React Bootstraped

3 / 45

Page 4: React Example + Bootstrap

Starter Kit - Cnt'd

4 / 45

Page 5: React Example + Bootstrap

5 / 45

Structure

react-15.4.1$ tree -L 2.|-- build|------ react-dom-fiber.js| |-- react-dom-fiber.min.js| |-- react-dom.js| |-- react-dom.min.js| |-- react-dom-server.js| |-- react-dom-server.min.js| |-- react.js| |-- react.min.js| |-- react-with-addons.js| |-- react-with-addons.min.js|-- examples| |-- basic| |-- basic-click-counter| |-- basic-commonjs| |-- basic-jsx| |-- basic-jsx-external| |-- basic-jsx-harmony| |-- basic-jsx-precompile| |-- fiber| |-- jquery-bootstrap| |-- jquery-mobile| |-- quadratic| |-- README.md| |-- shared| |-- transitions| |-- webcomponents|-- README.md

Page 6: React Example + Bootstrap

6 / 45

<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>Quadratic Formula Calculator</title> <link rel="stylesheet" href="../shared/css/base.css" /> </head> <body> <h1>Quadratic Formula Calculator</h1> <div id="container"> <p> If you can see this, React is <strong>not</strong> working right. This is probably because you&apos;re viewing this on your file system instead of a web server. Try running <pre> python -m SimpleHTTPServer </pre> and going to <a href="http://localhost:8000/">http://localhost:8000/</a>. </p> </div> <h4>Example Details</h4> <p>This is written with JSX in a separate file and transformed in the browser.</p> <p> Learn more about React at <a href="https://facebook.github.io/react" target="_blank">facebook.github.io/react</a>. </p> <script src="../../build/react.js"></script> <script src="../../build/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script <script type="text/babel" src="example.js"></script> </body></html>

quadraticHTML

Page 7: React Example + Bootstrap

getInitialState: function() { return { a: 1, b: 3, c: -4 }; },

/** * This function will be re-bound in render multiple times. Each .bind() will * create a new function that calls this with the appropriate key as well as * the event. The key is the key in the state object that the value should be * mapped from. */ handleInputChange: function(key, event) { var partialState = {}; partialState[key] = parseFloat(event.target.value); this.setState(partialState); },

render: function() { var a = this.state.a; var b = this.state.b; var c = this.state.c; var root = Math.sqrt(Math.pow(b, 2) - 4 * a * c); var denominator = 2 * a; var x1 = (-b + root) / denominator; var x2 = (-b - root) / denominator; return ( <div> <strong> <em>ax</em><sup>2</sup> + <em>bx</em> + <em>c</em> = 0 </strong> <h4>Solve for <em>x</em>:</h4> <p> <label> a: <input type="number" value={a} onChange={this.handleInputChange.bind(null, 'a')} /> </label> <br /> <label> b: <input type="number" value={b} onChange={this.handleInputChange.bind(null, 'b')} /> </label>

7 / 45

quadraticJS+JSXRequires babel

renderthis.stateMulti-Element...bind()

Page 8: React Example + Bootstrap

8 / 45

quadraticOne Component

Page 9: React Example + Bootstrap

</head> <body> <h1>Basic Example with WebComponents</h1> <div id="container"> <p> To install React, follow the instructions on <a href="http://www.github.com/facebook/react/">GitHub</a>. </p> <p> If you can see this, React is <strong>not</strong> working right. If you checked out the source from GitHub make sure to run <code>grunt</code>. </p> </div> <br /><br /> <h4>Example Details</h4> <p> This example demonstrates WebComponent/ReactComponent interoperability by rendering a ReactComponent, which renders a WebComponent, which renders another ReactComponent in the WebComponent's shadow DOM. <p> <p> Learn more about React at <a href="http://facebook.github.io/react" target="_blank">facebook.github.io/react</a>. </p> <script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.21/webcomponents.js" <script src="../../build/react.js"></script> <script src="../../build/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script

<script type="text/babel"> // Define WebComponent var proto = Object.create(HTMLElement.prototype, { attachedCallback: { value: function() { var mountPoint = document.createElement('span'); this.createShadowRoot().appendChild(mountPoint);

var name = this.getAttribute('name'); var url = 'https://www.google.com/search?q=' + encodeURIComponent(name); ReactDOM.render(<a href={url}>{name}</a>, mountPoint); } }

9 / 45

webcomponentsHTMLES2015+JSXRequires babel

this.props.name

Page 10: React Example + Bootstrap

10 / 45

webcomponentsOne Component

Page 11: React Example + Bootstrap

Learn more about React at <a href="https://facebook.github.io/react" target="_blank">facebook.github.io/react</a>. </p> <script src="../../build/react-with-addons.js"></script> <script src="../../build/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script <script type="text/babel"> var CSSTransitionGroup = React.addons.CSSTransitionGroup; var INTERVAL = 2000;

var AnimateDemo = React.createClass({ getInitialState: function() { return {current: 0}; },

componentDidMount: function() { this.interval = setInterval(this.tick, INTERVAL); },

componentWillUnmount: function() {

clearInterval(this.interval); },

tick: function() { this.setState({current: this.state.current + 1}); },

render: function() { var children = []; var pos = 0; var colors = ['red', 'gray', 'blue']; for (var i = this.state.current; i < this.state.current + colors.length; i++) { var style = { left: pos * 128, background: colors[i % colors.length] }; pos++; children.push(<div key={i} className="animateItem" style={style}>{i}</div>); } return ( <CSSTransitionGroup className="animateExample"

11 / 45

transitionsHTMLJS+JSXRequires babel..addons.js

this.state.current

Page 12: React Example + Bootstrap

.example-enter,

.example-leave { -webkit-transition: all .25s; transition: all .25s;}

.example-enter,

.example-leave.example-leave-active { opacity: 0.01;}

.example-enter.example-enter-active,

.example-leave { margin-left: 0; opacity: 1;}/* ------------------------------ */.example-leave.example-leave-active { margin-left: -128px;}

.example-enter { margin-left: 128px;}/* ------------------------------ */

.animateExample { display: block; height: 128px; position: relative; width: 384px;}

.animateItem { color: white; font-size: 36px; font-weight: bold; height: 128px; line-height: 128px; position: absolute; text-align: center; -webkit-transition: all .25s; /* TODO: make this a move animation */ transition: all .25s; /* TODO: make this a move animation */ 12 / 45

transitionsGlobal CSS

Inline Style provided by the Component

Page 13: React Example + Bootstrap

13 / 45

Layout

Page 14: React Example + Bootstrap

14 / 45

Enter & Leave

Page 15: React Example + Bootstrap

15 / 45

transitionsOne Component

Page 16: React Example + Bootstrap

16 / 45

<!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery Mobile React Example</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-mobile/1.4.5/jquery.mobile.min.css" <link rel="stylesheet" href="https://demos.jquerymobile.com/1.4.5/_assets/css/jqm-demos.css" /></head><body class="ui-mobile-viewport ui-overlay-a"> <div id="content"></div> <script src="http://code.jquery.com/jquery-2.2.2.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mobile/1.4.5/jquery.mobile.min.js"></ <script src="../../build/react.js"></script> <script src="../../build/react-dom.js"></script> <script src="js/app.js"></script></body></html>

jquery-mobileHTML

Page 17: React Example + Bootstrap

* | | |-- JQueryMobileButton * | |-- JQueryMobileFooter * |-- JQueryMobilePage (two) * | |-- JQueryMobileHeader * | |-- JQueryMobileContent * | | |-- PageTwoContent * | | |-- JQueryMobileButton * | |-- JQueryMobileFooter * |-- JQueryMobilePage (popup) * |-- JQueryMobileHeader * |-- JQueryMobileContent * | |-- PagePopUpContent * | |-- JQueryMobileButton * |-- JQueryMobileFooter */

/* global document, React */

'use strict';

/** Main application component. */var App = React.createClass({ displayName: 'App',

render: function() { return React.DOM.div({className:'app'}, JQueryMobilePage({id:'one'}, PageOneContent(null)), JQueryMobilePage({id:'two'}, PageTwoContent(null)), JQueryMobilePage({id:'popup', headerTheme:'b'}, PagePopUpContent(null)) );

}});App = React.createFactory(App);

/** jQuery Mobile page component. */var JQueryMobilePage = React.createClass({ displayName: 'JQueryMobilePage',

getDefaultProps: function() { return {'data-role':'page', 'data-theme':'a', headerTheme:'a'}; },

17 / 45

jquery-mobileJS

this.propsthis.props.children

Page 18: React Example + Bootstrap

/** jQuery Mobile button component. */var JQueryMobileButton = React.createClass({ displayName: 'JQueryMobileButton',

getDefaultProps: function() { return {className:'ui-btn ui-shadow ui-corner-all'}; },

render: function() { return React.DOM.p(null, React.DOM.a(this.props, this.props.children) ); }});JQueryMobileButton = React.createFactory(JQueryMobileButton);

/** jQuery Mobile page content component. */var JQueryMobileContent = React.createClass({ displayName: 'JQueryMobileContent',

render: function() { return React.DOM.div({role:'main', className:'ui-content'}, this.props.children ); }});JQueryMobileContent = React.createFactory(JQueryMobileContent);

/** jQuery Mobile footer component. */var JQueryMobileFooter = React.createClass({ displayName: 'JQueryMobileFooter',

render: function() { return React.DOM.div({'data-role':'footer'}, React.DOM.h4(null, 'Page footer') ); }});JQueryMobileFooter = React.createFactory(JQueryMobileFooter);

/** jQuery Mobile header component. */var JQueryMobileHeader = React.createClass({ displayName: 'JQueryMobileHeader', 18 / 45

jquery-mobileJS

Content as Children

Page 19: React Example + Bootstrap

19 / 45

Component TreeNotes: treatment of passedprops

Page 20: React Example + Bootstrap

jquery-mobile

20 / 45

Page 21: React Example + Bootstrap

React BootstrapedOr the Other Way Around

21 / 45

Page 22: React Example + Bootstrap

22 / 45

Structure

react-15.4.1$ tree -L 2.|-- build|------ react-dom-fiber.js| |-- react-dom-fiber.min.js| |-- react-dom.js| |-- react-dom.min.js| |-- react-dom-server.js| |-- react-dom-server.min.js| |-- react.js| |-- react.min.js| |-- react-with-addons.js| |-- react-with-addons.min.js|-- examples| |-- basic| |-- basic-click-counter| |-- basic-commonjs| |-- basic-jsx| |-- basic-jsx-external| |-- basic-jsx-harmony| |-- basic-jsx-precompile| |-- fiber| |-- jquery-bootstrap| |-- jquery-mobile| |-- quadratic| |-- README.md| |-- shared| |-- transitions| |-- webcomponents|-- README.md

Page 23: React Example + Bootstrap

23 / 45

<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>jQuery Integration</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" <style> .example { margin: 20px; } </style> </head> <body> <div id="jqueryexample"></div> <script src="../../build/react.js"></script> <script src="../../build/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script <script src="http://code.jquery.com/jquery-2.2.2.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" <script type="text/babel" src="js/app.js"></script> </body></html>

jquery-bootstrapHTML

Page 24: React Example + Bootstrap

'use strict';

var Example = React.createClass({ handleCancel: function() { if (confirm('Are you sure you want to cancel?')) { this.refs.modal.close(); } }, render: function() { var modal = null; modal = ( <BootstrapModal ref="modal" confirm="OK" cancel="Cancel" onCancel={this.handleCancel} onConfirm={this.closeModal} onHidden={this.handleModalDidClose} title="Hello, Bootstrap!"> This is a React component powered by jQuery and Bootstrap! </BootstrapModal> ); return ( <div className="example"> {modal} <BootstrapButton onClick={this.openModal} className="btn-default"> Open modal </BootstrapButton> </div> ); }, openModal: function() { this.refs.modal.open(); }, closeModal: function() { this.refs.modal.close(); }, handleModalDidClose: function() { alert("The modal has been dismissed!"); }});

ReactDOM.render(<Example />, document.getElementById('jqueryexample')); 24 / 45

jquery-bootstrapJS+JSXRequires babel

this.refs.modal

Page 25: React Example + Bootstrap

// Simple pure-React component so we don't have to remember// Bootstrap's classesvar BootstrapButton = React.createClass({ render: function() { return ( <a {...this.props} href="javascript:;" role="button" className={(this.props.className || '') + ' btn'} /> ); }});

var BootstrapModal = React.createClass({ // The following two methods are the only places we need to // integrate Bootstrap or jQuery with the components lifecycle methods. componentDidMount: function() { // When the component is added, turn it into a modal $(this.refs.root).modal({backdrop: 'static', keyboard: false, show: false});

// Bootstrap's modal class exposes a few events for hooking into modal // functionality. Lets hook into one of them: $(this.refs.root).on('hidden.bs.modal', this.handleHidden); }, componentWillUnmount: function() { $(this.refs.root).off('hidden.bs.modal', this.handleHidden); },

close: function() { $(this.refs.root).modal('hide'); }, open: function() { $(this.refs.root).modal('show'); }, render: function() { var confirmButton = null; var cancelButton = null;

if (this.props.confirm) { confirmButton = ( <BootstrapButton onClick={this.handleConfirm} className="btn-primary"> 25 / 45

jquery-bootstrapJS+JSXRequires babel

...this.propsthis.refs.root

Page 26: React Example + Bootstrap

26 / 45

Component TreeStateless Component

Page 27: React Example + Bootstrap

27 / 45

jquery-bootstrapafter openModal

Page 28: React Example + Bootstrap

28 / 45

jquery-bootstraphandleCancel

Page 29: React Example + Bootstrap

29 / 45

jquery-bootstrapafter closeModalhandleModalDidClose

Page 30: React Example + Bootstrap

30 / 45

BS Docs

Page 31: React Example + Bootstrap

31 / 45

BS Docs

Page 32: React Example + Bootstrap

32 / 45

BS DocsjQuery .off() to removeevent handlers (after hide)attached with the .on()method (after modal show).

Page 33: React Example + Bootstrap

<!DOCTYPE html><html ><head> <meta charset="UTF-8"> <title>React Example</title>

<link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' <style>.container {padding: 20px;} </style></head>

<body> <main class="container"></main>

<script src="build/react.js"></script> <script src="build/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script

<script type="text/babel" src="babel/index.babel"></script></body></html>

33 / 45

Extra #1HTML Ref: React Example @codepen

BS CSS Only

Page 34: React Example + Bootstrap

class Nav extends React.Component { constructor(props) { super(props); this.state = {selected: 0}; }

setActive(index) { this.setState(Object.assign(this.state, {selected: index})); //this.setState({selected: index}); }

renderItems() { return this.props.items.map((item, i)=> { return ( <li className={ i === this.state.selected ? 'active' : ''}> <a href="#" onClick={()=> this.setActive(i) }> {item} </a> </li> ); }); }

render() { return <ul className="nav nav-pills">{ this.renderItems() }</ul>; }}

const navItems = [ 'Home', 'About', 'Contact'];

ReactDOM.render(<Nav items={navItems} />, document.querySelector('main'));

34 / 45

Extra #1ES2015+JSXRequires babel

One Componentthis.state

Page 35: React Example + Bootstrap

35 / 45

Extra #1

Page 36: React Example + Bootstrap

36 / 45

Extra #2Structure

Ref: fedosejev @GitHub

fedosejev$ tree.|-- data.json|-- images| |-- IMG_5774.jpg| |-- IMG_6305.jpg| |-- IMG_6701.jpg| |-- IMG_6732.jpg| |-- IMG_6795.jpg|-- index.html|-- js| |-- app.jsx| |-- components| |-- Application.jsx| |-- Image.jsx|-- package.json

3 directories, 11 files

Page 37: React Example + Bootstrap

37 / 45

npmpackage.json

{ "name": "fedosejev-example", "description": "fedosejev React example", "private": true, "main": "js/app.jsx", "dependencies": { "babel-preset-es2015": "̂6.6.0", "babel-preset-react": "̂6.5.0", "babelify": "̂7.3.0", "browserify": "̂13.0.0", "react": "̂15.0.2", "react-dom": "̂15.0.2", "watchify": "̂3.7.0" }, "scripts": { "build": "browserify js/app.jsx -t babelify -o js/app.js", "start": "watchify js/app.jsx -v -t babelify -o js/app.js" }}

$ npm start> fedosejev-example@ start /home/em/fedosejev> watchify js/app.jsx -v -t babelify -o js/app.js

723589 bytes written to js/app.js (6.14 seconds)

Page 38: React Example + Bootstrap

38 / 45

<!doctype html><html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="x-ua-compatible" content="ie=edge, chrome=1" /> <title>Application</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" </head> <body> <div data-react-application> <h5 class="text-center text-muted">Loading application...</h5> </div>

<script src="./js/app.js"></script> </body></html>

{ "images": [ "IMG_5774.jpg", "IMG_6305.jpg", "IMG_6701.jpg", "IMG_6732.jpg", "IMG_6795.jpg" ]}

Extra #2HTMLdata.json

BS CSS Only

Page 39: React Example + Bootstrap

39 / 45

$ tree.|-- data.json|-- images| |-- IMG_5774.jpg| |-- IMG_6305.jpg| |-- IMG_6701.jpg| |-- IMG_6732.jpg| |-- IMG_6795.jpg|-- index.html|-- js| |-- app.jsx| |-- components| |-- Application.jsx| |-- Image.jsx|-- package.json

import React from 'react';import ReactDOM from 'react-dom';import Application from './components/Application.jsx';

ReactDOM.render(<Application />, document.querySelector('[data-react-application]'));

Extra #2js/app.jsx

Page 40: React Example + Bootstrap

import React from 'react';import Image from './Image.jsx';import data from '../../data.json';

let Application = React.createClass({ createImage: function (image) { return <Image source={image} key={image} />; },

createImages: function (images) { return images.map(this.createImage); },

render: function () { return ( <div className="container"> <div className="row"> <div className="col-sm-12 text-center">

{this.createImages(data.images)}

</div> </div> </div> ); }});

export default Application;

/* ------------------------------------------ */

import React from 'react';

let Image = function statelessFunctionComponentClass(props) { let source = './images/' + props.source;

let style = { width: '200px', margin: '10px 5px 0px 5px' };

return ( <img src={source} style={style} /> 40 / 45

Extra #2c/Application.jsxc/Image.jsx

ES2015+JSX

Two Componentskey={} react internal (cf. transitions)

Page 41: React Example + Bootstrap

41 / 45

Extra #2

Page 42: React Example + Bootstrap

Refs

42 / 45

Page 43: React Example + Bootstrap

Refs1. A JavaScript library for building user interfaces | React2. facebook/react: A declarative, e�cient, and �exible JavaScript library for building user

interfaces.3. Intro and Concept - Learning React4. React Example5. JavaScript - Bootstrap6. fedosejev/how-to-create-react-components-dynamically

43 / 45

Page 44: React Example + Bootstrap

44 / 45

ENDEueung Mulyana

https://eueung.github.io/112016/react-expCodeLabs | Attribution-ShareAlike CC BY-SA

Page 45: React Example + Bootstrap

45 / 45

That's Allfor the basics ...piece of cake, no?