Презентация

ReactJS: creating React components with JSX - JS Applications - ноември 2016

 

Материали от темата

Съдържание на документа

React – JS UI Library

Creating React Components
with JSX and Babel

SoftUni Team

Technical Trainers

Software University

http://softuni.bg

ReactJS


Table of Contents

ReactJS – Overview

In-Browser Transpilation

Setup a Server-Side Build

Creating JSX Components



2


3



sli.do
#react

Have a Question?


ReactJS – Overview

A JS Library for Building User Interfaces


5

React (ReactJS / React.js) – https://facebook.github.io/react/

A JavaScript library for building user interfaces (UI)

Open-source, declarative, component-based, by Facebook

What is React?

class HelloMessage extends React.Component {

  render() {

    return <div>Hello {this.props.name}</div>;

  }

}

ReactDOM.render(<HelloMessage name="Maria" />,

  document.getElementById('container'));


Setup React in the Browser


7

In-browser React transpilation with "babel-standalone"

Running React in the Browser

<script src="https://unpkg.com/react/dist/react.js"></script>

<script src="https://unpkg.com/react-dom/dist/react-dom.js"></script>

<script src="https://unpkg.com/babel-standalone"></script>

<div id="app">A React component will be rendered here</div>

<script type="text/babel">

  ReactDOM.render(<div>Hello, React!</div>,

    document.getElementById('app'));

</script>


Setup React Server-Side Build

Configuring the Development Environment


9

Install the React app creator (on-time global install):



Run the React app creator (this is very slow: ~5-10 minutes!)



Starts your React app from the command line



Browse you app from http://localhost:3000

Install and Run the React App Creator

npm -g install create-react-app

create-react-app react-example

npm start


10

React Apps with WebStorm


11

package.json – project configuration

Module name, dependencies, build actions

index.html

App main HTML file

index.js

App main JS file (startup script)

App.js, App.css, App.test.js

React component "App"

React App Structure


Creating JSX Components

JSX

component


13

JSX is a React's syntax for mixing HTML with JavaScript

What is JSX?

let element =

  <h1>Hello, <b>React</b>!</h1>;

console.dir(element);

let age = 18;

let ageElement =

  <p>Age: {age}</p>;

ReactDOM.render(ageElement,

  document.getElementById('app'));




14

Creating a JSX Component (with Class)

class Person extends React.Component {

  render() {

    return (

      <div>

        <h1>{this.props.person}</h1>

        <p>Tel. {this.props.phone}</p>

      </div>

    )

  }

}



ReactDOM.render(

  <Person person="Nakov"

    phone="+359 2 981 981" />,

  document.getElementById('app')

); 


15

Creating a JSX Component (with Object)

let Person = React.createClass({

  render: function() {

    return (

      <div>

        <h1>{this.props.person}</h1>

        <p>Tel. {this.props.phone}</p>

      </div>

    )

  }

});



ReactDOM.render(

  <Person person="Nakov"

    phone="+359 2 981 981" />,

  document.getElementById('app')

); 


16

Creating a JSX Component (with Function)

function ErrorBox(props) {

  let css = {

    color: 'red', fontWeight: 'bold',

    border: '1px solid red', padding: '8px'

  };

  return <div style={css}>Error: {props.msg}</div>;

}

ReactDOM.render(

  <ErrorBox msg='Invalid login!' />,

  document.getElementById('app')

);


17

Component Holding a State

let Counter = React.createClass({

  getInitialState: function() {

    return { count: this.props.start }

  },

  render: function() {

    return <h1>Count: {this.state.count}</h1>

  }

});





ReactDOM.render(

  <Counter start="5" />,

  document.getElementById('app'));


18

Component Holding a State + Events

let Counter = React.createClass({

  getInitialState: function() {

    return { count: Number(this.props.start) }

  },

  incrementCount: function() { this.changeCount(+1) },

  decrementCount: function() { this.changeCount(-1) },

  changeCount: function(delta) {

    // This will update the component UI

    this.setState({

      count: this.state.count + delta

    });

  },


19

Component Holding a State + Events

  render: function() {

    return <div>

        Count: {this.state.count}

        <button type="button" onClick=

           {this.incrementCount}>+</button>

        <button type="button" onClick=

           {this.decrementCount}>-</button>

      </div>

  }

});

let counter = <Counter start="5" />;

ReactDOM.render(counter, document.getElementById('app'));


20

React Dev Tools – https://github.com/facebook/react-devtools

Using the React Developer Tools


21

Rendering a List of Items (with Loop)

let List = React.createClass({

  render: function() {

    let items = [];

    for (let i in this.props.items)

      items.push(<li key={i}>{this.props.items[i]}</li>);

    return <ul>{items}</ul>;

  }

});

let towns = ["Sofia", "Varna", "Plovdiv"];

let list = <List items={towns} />;

ReactDOM.render(list, document.getElementById('app'));


22

Rendering a List of Items (with .map())

let List = React.createClass({

  render: function() {

    let items = this.props.items.map(function(item, i) {

      return <li key={i}>{item}</li>;

    });

    return <ul>{items}</ul>;

  }

});



let list = <List items={["Sofia", "Varna", "Plovdiv"]} />;

ReactDOM.render(list, document.getElementById('app'));


23

Rendering a List of Items (Inline)

let List = React.createClass({

  render: function() {

    return (

      <ul>

        {this.props.items.map(function(item, i) {

          return <li key={i}>{item}</li>;

        })}

      </ul>

    )

  }

});

ReactDOM.render(

  <List items={["Sofia", "Varna", "Plovdiv"]} />,

  document.getElementById('app'));


24

Rendering a Table of Rows

let Table = React.createClass({

  render: function() {

    let titles = 

      this.props.columns.map(function(column, i) {

        return <th key={i}>{column}</th>;

      });

    let rows = this.props.rows.map(function(row, r) {

      return <tr key={r}>{row.map(function(col, c){

        return <td key={c}>{col}</td>

      })}</tr>;

    });        


25

Rendering a Table of Rows (2)

    return (

      <table>

        <thead><tr>{titles}</tr></thead>

        <tbody>{rows}</tbody>

      </table>

    )

  }

});

let books = [["JS Programming Basics","Bay Ivan"],

  ["PHP","Dedo Mraz"], ["React.js","Kaka Mara"]];

ReactDOM.render(

  <Table columns={["Title", "Author"]} rows={books} />,

  document.getElementById('app'));


26

Rendering Forms (Controlled Component)

let PersonForm = React.createClass({

  getInitialState: function() {

    let name = this.props.name;

    if (name == undefined) name = "";

    let age = Number(this.props.age);

    if (Number.isNaN(age)) age = 0;

    return { name, age };

  },

  handleNameChange(event) {

    this.setState({name: event.target.value});

  },


27

Rendering Forms (Controlled Component) (2)

  handleAgeChange(event) {

    let age = Number(event.target.value);

    if (Number.isNaN(age))

      age = 0;

    this.setState({ age });

  },

  handleFormSubmit(event) {

    if (this.props.onsubmit)

      this.props.onsubmit(this.state);

    event.preventDefault();

  },


28

Rendering Forms (Controlled Component) (3)

  render: function() {

    return <form onSubmit={this.handleFormSubmit}>

      <label>Name:

        <input type="text" value={this.state.name}

          onChange={this.handleNameChange} />

      </label>

      <label>Age:

        <input type="text" value={this.state.age}

          onChange={this.handleAgeChange} />

      </label>

      <input type="submit" value="Submit" />

    </form>

  }

});


29

Rendering Forms (Controlled Component) (4)

ReactDOM.render(

  <div>

    <PersonForm />

    <PersonForm onsubmit={editPerson} />

    <PersonForm name="Nakov" age="20"

      onsubmit={editPerson} />

  </div>,

  document.getElementById('app'));



function editPerson(personFormData) {

  alert(JSON.stringify(personFormData));

}


30

Rendering Forms (Uncontrolled Component)

let PersonForm = React.createClass({

  render: function() {

    return <form onSubmit={this.handleFormSubmit}>

      <label>Name:

        <input type="text" defaultValue={this.props.name}

         ref={e => this.nameField = e} />

      </label>

      <label>Age:

        <input type="text" defaultValue={this.props.age}

         ref={e => this.ageField = e} />

      </label>

      <input type="submit" />

    </form>

  },

Remember the undelying DOM element as field


31

Rendering Forms (Uncontrolled Component) (2)

  handleFormSubmit: function(event) {

    event.preventDefault();

    let formData = {

      name: this.nameField.value,

      age: this.ageField.value

    };

    if (this.props.onsubmit)

      this.props.onsubmit(formData);

  }

});

Take the form field values from the underlying DOM elements


32

Rendering Forms (Uncontrolled Component) (3)

ReactDOM.render(

  <div>

    <PersonForm name="Dev" onsubmit={editPerson} />

    <PersonForm age="18" onsubmit={editPerson} />

    <PersonForm name="Nakov" age="20" 

      onsubmit={editPerson} />

  </div>,

  document.getElementById('app'));



function editPerson(personFormData) {

  alert(JSON.stringify(personFormData));

}


33

React and jQuery

<script src="jquery.min.js"></script>



let Hello = React.createClass({

  render: function() {

    return <p>Hello, {this.props.name}</p>

  }

});



let div = $('<div>').appendTo(document.body);

ReactDOM.render(<Hello name='Maria' />, div[0]);

div holds jQuery collection

 div[0] holds DOM element


Practice: React and JSX Components

Live Exercises in Class (Lab)

JSX

component


35

ReactJS: open-source, declarative, component-based UI library for JS

React DOM uses JSX syntax

Summary

let HelloMsg = React.createClass({

  render: function() {

    return <p>Hello {this.props.name}</p>;

  }

});

ReactDOM.render(<HelloMsg name="Maria" />,

  document.getElementById('container'));


https://softuni.bg/courses/javascript-applications

ReactJS


License

This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International" license

37


Free Trainings @ Software University

Software University Foundation – softuni.org

Software University – High-Quality Education, Profession and Job for Software Developers

softuni.bg 

	Software University @ Facebook

	facebook.com/SoftwareUniversity

	Software University @ YouTube

	youtube.com/SoftwareUniversity

	Software University Forums – forum.softuni.bg