+2347067162698
tclassified.com@gmail.com

Reactjs Stack up

Educational Technology and ICT

Created with Sketch.

Reactjs Stack up

react is a javascript librarymaintened and used by facebook and also used by ebay, newyorktimes, pintrest

check whether you have node
node –help
Installing Yarn
Yarn is a package manager for Nodejs. Were going to use it install create-react-app and get ourselves set up with a working React application.
Go to the installation page for the yarn project and select the tab for your operating system. Follow the instructions there to install Yarn on your machine.

yarn global add create-react-app
create-react-app –help

Create a React app!

create-react-app frtapp
inspect the folders and files created
cd frtapp
yarn start

check localhost 3000 is automatically up serving the react app

inspect the folders installed and check how app is mounted on webpages

build a component

Components and props
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

props is an object available on this inside a component class that gives you access to the values that were passed when a component was called. It’s like the arguments in a function.

Components can be either functions or objects in React. In this course, we’re using the object form of components exclusively. In the case of a component that was defined as a function, though, props will be available as a function parameter instead of a property on this .

To see how they work, let’s edit the App component.

copy and replace what is on the vscode in app.js
………………………………
class Welcome extends React.Component {
render() {
return

Hello, {this.props.name}

;
}
}
……………………………

Change the message on line 14 to say:
Hi {this.props.name}!

Do you remember where this component is called? It’s in index.js . Go there now and pass your first name as a prop to the App component.
from to   

Next, let’s try a variable. Declare a variable with the value of your name as a string. Then, instead of a quoted string, pass it as the value for the name prop by putting it inside a template expression:

let name = “alex”;

ReactDOM.render(
,
document.getElementById(‘root’)
);

Props are read-only
Inside your component, you should only access this.props to read values. You should never modify the this.props property.

Root element
Components always need to have one top-level element. If you have a component that looks like this:

class Foo extends Component {
render() {
return (
… Foo things
… other stuff
);
}
}

should be this
class Foo extends Component {
render() {
return (
… Foo things
… other stuff

);
}
}

Build a ticking clock component
Displaying the time
Back in App.js, declare a variable time and then display it inside a new

element at the bottom of the component:

let time = new Date().toLocaleString();

class App extends Component {
render() {
return (
logo

Welcome to React

Hi {this.props.name}!

The time is {time}.

);
}
}

Breaking the code out into a new component
Let’s remove the whole

tag and its contents that we created to display the time, and move it to a new file called src/Clock.js . Remember that we need the React object in scope to make JSX work, so let’s import it at the top of the page, and define a new component class just as was done for us in the App component. Let’s skip the destructuring in the import statement at the top so we can see more simply what’s going on here:

import React from ‘react’;

let time = new Date().toLocaleString();

class Clock extends React.Component {
render() {
return (

The time is {time}.
);
}
}
export default Clock;

the app component becomes

class App extends Component {
render() {
return (
logo

Welcome to React

Hi {this.props.name}!


);
}
}

using state

import React from ‘react’;

class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
time: new Date().toLocaleString()
};
}
render() {
return (

The time is {this.state.time}.
);
}
}

export default Clock;

note state is private

Making the clock tick with lifecycle hooks

class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
time: new Date().toLocaleString()
};
}
componentDidMount() {
this.intervalID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
tick() {
this.setState({
time: new Date().toLocaleString()
});
}
render() {
return (

The time is {this.state.time}.
);
}
}

Using props and state while setting state
change this
………….
doTheMultiplication() {
this.setState({
value: this.state.thingToMultiply * this.props.multiplier
});
}

to
………………….
doTheMultiplication() {
this.setState(function (prevState, props) {
return {
value: prevState.thingToMultiply * props.multiplier
};
});
}

Handle events
……………………

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
console.log(this);
}
render() {
return (
Click me
);
}
}

Understand one-way data bindings
…………………..
In React, Data Only Goes One Way!

React apps are organized as a series of nested components. These components are functional in nature: that is, they receive information through arguments (represented in the props attribute) and pass information via their return values (the return value of the render function). This is called unidirectional data flow. Data is passed down from components to their children.

Components should never try to read or modify the DOM directly. If you find yourself writing selectors to access elements on the page, you’re probably doing it wrong.

Challenge:
What if our spec requires us to reference the current color of the background inside the button? Change the button component so that its text is just “I don’t like red” when the current color is red, and “I don’t like blue” when the current color is blue. Remember, ChangeColorButton should get all information about its parent’s state through its props attribute.

Solution:
ChangeColorButton.js :

import React from ‘react’;

class ChangeColorButton extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.clickHandler();
}
render() {
return (
I dont like {this.props.currentColor}
);
}
}

export default ChangeColorButton;
ColoredBlock.js :

import React from ‘react’;
import ChangeColorButton from ‘./ChangeColorButton.js’;

class ColoredBlock extends React.Component {
constructor(props) {
super(props);
this.changeColor = this.changeColor.bind(this);
this.state = {
color: ‘red’
};
}
changeColor() {
this.setState((prevState, props) => ({
color: prevState.color === ‘red’ ? ‘blue’ : ‘red’
}));
}
render() {
return (

)
}
}

export default ColoredBlock;
State updates may be asynchronous
You may have noticed that setState is used in a different way above than in our ticking clock example. You might wonder why didn’t we write it like this:

changeColor() {
this.setState({
color: this.state.color === ‘red’ ? ‘blue’ : ‘red’
});
}
That’s because state updates may be asynchronous, and you actually can’t rely on this.state or this.props when calculating the new state. The solution is to use the alternate callback syntax for setState

Building a react app
by example and adding the validation needed

study the reqirements by the client
break the requirements into componects
check the msword in this folder for it

then start
the app structure is
…………………………………………..
Products
Filters
Product Form
Product Table
Product Table Headers
Product Row
………………………………………….
app.js

import React from ‘react’;
import Products from ‘./Products.js’;

class App extends React.Component {
render() {
return (

My React App

);
}
}

export default App;
……………………………………………………
Products.js

import React from ‘react’;
import Filters from ‘./Filters.js’;
import ProductForm from ‘./ProductForm’;
import ProductTable from ‘./ProductTable.js’;

var PRODUCTS = {
‘1’: {id: 1, category: ‘Musical Instruments’, price: ‘$459.99’, stocked: true, name: ‘Clarinet’},
‘2’: {id: 2, category: ‘Musical Instruments’, price: ‘$5,000’, stocked: true, name: ‘Cello’},
‘3’: {id: 3, category: ‘Musical Instruments’, price: ‘$11,000’, stocked: false, name: ‘Fortepiano’},
‘4’: {id: 4, category: ‘Furniture’, price: ‘$799’, stocked: true, name: ‘Chaise Lounge’},
‘5’: {id: 5, category: ‘Furniture’, price: ‘$1,300’, stocked: false, name: ‘Dining Table’},
‘6’: {id: 6, category: ‘Furniture’, price: ‘$100’, stocked: true, name: ‘Bean Bag’}
};

class Products extends React.Component {
render() {
return (

);
}
}

export default Products;
……………………………………………………
Filters.js

import React from ‘react’;

class Filters extends React.Component {
render() {
return (

 Only show stocked products
);
}
}

export default Filters;
……………………………………………………
ProductTable.js

import React from ‘react’;
import ProductRow from ‘./ProductRow.js’;
import ProductTableHeader from ‘./ProductTableHeader.js’;

class ProductTable extends React.Component {
render() {
let productsAsArray = Object.keys(this.props.products).map((pid) => this.props.products[pid]);
let rows = [];

productsAsArray.forEach((product) => {
  rows.push(
    <ProductRow product={product} key={product.id} ></ProductRow>
  );
});

return (
  <div>
    <table>
      <thead>
        <tr>
          <ProductTableHeader column="name" ></ProductTableHeader>
          <ProductTableHeader column="price" ></ProductTableHeader>
        </tr>
      </thead>
      <tbody>{rows}</tbody>
    </table>
  </div>
);

}
}

export default ProductTable;
……………………………………………………
ProductTableHeader.js

import React from ‘react’;
import ‘./ProductTableHeader.css’;

class ProductTableHeader extends React.Component {
render() {
return(
{this.props.column} ▲ ▼
);
}
}

export default ProductTableHeader;
……………………………………………………
ProductTableHeader.css

.ProductTableHeader-current {
background-color: #0ff;
}
……………………………………………………
ProductRow.js

import React from ‘react’;
import ‘./ProductRow.css’;

class ProductRow extends React.Component {
render() {
return (
{this.props.product.name} {this.props.product.price} x
);
}
}

export default ProductRow;
……………………………………….
ProductRow.css

.ProductRow-out-of-stock {
color: red;
}

………………………………………………………
ProductForm.js

import React from ‘react’;

class ProductForm extends React.Component {
render() {
return (

Enter a new product

Name

Category

Price

 In stock?
);
}
}

export default ProductForm;
……………………………………………

Identify State
…………………..

state change are those information that can change due to user interaction
………………………..
Product.js

import React from ‘react’;
import Filters from ‘./Filters.js’;
import ProductTable from ‘./ProductTable.js’;
import ProductForm from ‘./ProductForm’;

var PRODUCTS = {
‘1’: {id: 1, category: ‘Musical Instruments’, price: ‘$459.99’, stocked: true, name: ‘Clarinet’},
‘2’: {id: 2, category: ‘Musical Instruments’, price: ‘$5,000’, stocked: true, name: ‘Harpsicord’},
‘3’: {id: 3, category: ‘Musical Instruments’, price: ‘$11,000’, stocked: false, name: ‘Fortepiano’},
‘4’: {id: 4, category: ‘Furniture’, price: ‘$799’, stocked: true, name: ‘Chaise Lounge’},
‘5’: {id: 5, category: ‘Furniture’, price: ‘$1,300’, stocked: false, name: ‘Dining Table’},
‘6’: {id: 6, category: ‘Furniture’, price: ‘$100’, stocked: true, name: ‘Bean Bag’}
};

class Products extends React.Component {
constructor(props) {
super(props);
this.state = {
filterText: ”,
inStockOnly: false,
products: PRODUCTS
};

}
render() {
return (

);
}
}

export default Products;

……………………………..
Filter.js

import React from ‘react’;

class Filters extends React.Component {
render() {
return (

  Only show products in stock
);
}
}

export default Filters;

……………………..

ProductTable.js

import React from ‘react’;
import ProductRow from ‘./ProductRow.js’;
import SortableColumnHeader from ‘./SortableColumnHeader.js’;

class ProductTable extends React.Component {
constructor(props) {
super(props);
this.sortByKeyAndOrder = this.sortByKeyAndOrder.bind(this);
this.state = {
sort: {
column: ‘name’,
direction: ‘desc’
}
};
}
sortByKeyAndOrder(objectA, objectB) {
let isDesc = this.state.sort.direction === ‘desc’ ? 1 : -1;
let [a, b] = [objectA[this.state.sort.column], objectB[this.state.sort.column]];
if (this.state.sort.column === ‘price’) {
[a, b] = [a, b].map((value) => parseFloat(value.replace(/[^\d.]/g, ”), 10));
}
if (a > b) {
return 1 * isDesc;
}
if (a < b) { return -1 * isDesc; } return 0; } sortProducts() { let productsAsArray = Object.keys(this.props.products).map((pid) => this.props.products[pid]);
return productsAsArray.sort(this.sortByKeyAndOrder);
}
render() {
var rows = [];
this.sortProducts().forEach((product) => {
if (product.name.indexOf(this.props.filterText) === -1 || (!product.stocked && this.props.inStockOnly)) {
return;
}
rows.push();
});

return (
  <div>
    <table>
      <thead>
        <tr>
          <SortableColumnHeader
            currentSort={this.state.sort}
            column="name"
          ></SortableColumnHeader>
          <SortableColumnHeader
            currentSort={this.state.sort}
            column="price"
          ></SortableColumnHeader>
        </tr>
      </thead>
      <tbody>{rows}</tbody>
    </table>
  </div>
);

}
}

export default ProductTable;

…………………………………..

SortableColumnHeader.js

import React from ‘react’;
import ‘./SortableColumnHeader.css’;

class SortableColumnHeader extends React.Component {
render() {
let currentSort = this.props.currentSort.column === this.props.column ? this.props.currentSort.direction : false;
return(
{this.props.column} ▲ ▼
);
}
}

export default SortableColumnHeader;
………………………………………

Handle User Imput

this is the use of event handling to update state
they call setState to do this

……………………….
The complexity here lies in letting a child component’s events affect its parent’s state. The DOM’s pattern for this type of communication is to bubble events up the DOM tree. By contrast, instead of explicitly bubbling actions up, we’ll pass handlers down – just like any other kind of information, via props – that when called, will make the necessary changes to the parent’s state.

To illustrate how to handle events by passing handlers down, we’ll start at the top of our component tree again.

The component’s state is affected by three user actions that are triggered in descendent components:

filtering the list of products

submitting the new product form

destroying products

Let’s start with filtering the list of products. We simply want to set our local state to match whatever data is triggered in the component. This involves

writing a simple handler that takes input and passes it to setState :
………………………………

Products.js

import React from ‘react’;
import Filters from ‘./Filters.js’;
import ProductTable from ‘./ProductTable.js’;
import ProductForm from ‘./ProductForm’;

var PRODUCTS = {
‘1’: {id: 1, category: ‘Musical Instruments’, price: ‘$459.99’, stocked: true, name: ‘Clarinet’},
‘2’: {id: 2, category: ‘Musical Instruments’, price: ‘$5,000’, stocked: true, name: ‘Harpsicord’},
‘3’: {id: 3, category: ‘Musical Instruments’, price: ‘$11,000’, stocked: false, name: ‘Fortepiano’},
‘4’: {id: 4, category: ‘Furniture’, price: ‘$799’, stocked: true, name: ‘Chaise Lounge’},
‘5’: {id: 5, category: ‘Furniture’, price: ‘$1,300’, stocked: false, name: ‘Dining Table’},
‘6’: {id: 6, category: ‘Furniture’, price: ‘$100’, stocked: true, name: ‘Bean Bag’}
};

class Products extends React.Component {
constructor(props) {
super(props);
this.state = {
filterText: ”,
inStockOnly: false,
products: PRODUCTS
};

this.handleFilter = this.handleFilter.bind(this);
this.handleDestroy = this.handleDestroy.bind(this);
this.saveProduct = this.saveProduct.bind(this);

}
handleFilter(filterInput) {
this.setState(filterInput);
}
saveProduct(product) {
if (!product.id) {
product.id = new Date().getTime();
}
this.setState((prevState) => {
let products = prevState.products;
products[product.id] = product;
return { products };
});
}
handleDestroy(productId) {
this.setState((prevState) => {
let products = prevState.products;
delete products[productId];
return { products };
});
}
render() {
return (

);
}
}

export default Products;

………………………………………
Filters.js

import React from ‘react’;

class Filters extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
const value = e.target[e.target.type === “checkbox” ? “checked” : “value”]
const name = e.target.name;

this.props.onFilter({
  [name]: value
});

}
render() {
return (

  Only show products in stock
);
}
}

export default Filters;

……………………………..
ProductForm.js

import React from ‘react’;

const RESET_VALUES = {id: ”, category: ”, price: ”, stocked: false, name: ”};

class ProductForm extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSave = this.handleSave.bind(this);
this.state = {
product: Object.assign({}, RESET_VALUES),
errors: {}
};
}
handleChange(e) {
const target = e.target;
const value = target.type === ‘checkbox’ ? target.checked : target.value;
const name = target.name;

this.setState((prevState) => {
  prevState.product[name] = value;
  return { product: prevState.product };
});

}
handleSave(e) {
this.props.onSave(this.state.product);
this.setState({
product: Object.assign({}, RESET_VALUES),
errors: {}
});
e.preventDefault();
}
render() {
return (

Enter a new product

Name

Category

Price

 In stock?
);
}
}

export default ProductForm;
…………………………………
ProductTable.js

import React from ‘react’;
import ProductRow from ‘./ProductRow.js’;
import SortableColumnHeader from ‘./SortableColumnHeader.js’;

class ProductTable extends React.Component {
constructor(props) {
super(props);
this.sortByKeyAndOrder = this.sortByKeyAndOrder.bind(this);
this.handleSort = this.handleSort.bind(this);
this.handleDestroy = this.handleDestroy.bind(this);
this.state = {
sort: {
column: ‘name’,
direction: ‘desc’
}
};
}
sortByKeyAndOrder(objectA, objectB) {
let isDesc = this.state.sort.direction === ‘desc’ ? 1 : -1;
let [a, b] = [objectA[this.state.sort.column], objectB[this.state.sort.column]];
if (this.state.sort.column === ‘price’) {
[a, b] = [a, b].map((value) => parseFloat(value.replace(/[^\d.]/g, ”), 10));
}
if (a > b) {
return 1 * isDesc;
}
if (a < b) { return -1 * isDesc; } return 0; } sortProducts() { let productsAsArray = Object.keys(this.props.products).map((pid) => this.props.products[pid]);
return productsAsArray.sort(this.sortByKeyAndOrder);
}
handleDestroy(id) {
this.props.onDestroy(id);
}
handleSort(column, direction) {
this.setState({
sort: {
column: column,
direction: direction
}
});
}
render() {
var rows = [];
this.sortProducts().forEach((product) => {
if (product.name.indexOf(this.props.filterText) === -1 || (!product.stocked && this.props.inStockOnly)) {
return;
}
rows.push();
});

return (
  <div>
    <table>
      <thead>
        <tr>
          <SortableColumnHeader
            onSort={this.handleSort}
            currentSort={this.state.sort}
            column="name"
          ></SortableColumnHeader>
          <SortableColumnHeader
            onSort={this.handleSort}
            currentSort={this.state.sort}
            column="price"
          ></SortableColumnHeader>
        </tr>
      </thead>
      <tbody>{rows}</tbody>
    </table>
  </div>
);

}
}

export default ProductTable;

…………………………………
SortableColumnHeader.js

import React from ‘react’;
import ‘./SortableColumnHeader.css’;

class SortableColumnHeader extends React.Component {
constructor(props) {
super(props);
this.handleSort = this.handleSort.bind(this);
}
handleSort(e) {
this.props.onSort(this.props.column, e.target.name);
}
render() {
let currentSort = this.props.currentSort.column === this.props.column ? this.props.currentSort.direction : false;
return(
{this.props.column} ▲ ▼
);
}
}

export default SortableColumnHeader;

……………………………….
ProductRow.js

import React from ‘react’;

class ProductRow extends React.Component {
constructor(props) {
super(props);
this.destroy = this.destroy.bind(this);
}
destroy() {
this.props.onDestroy(this.props.product.id);
}
render() {
var name = this.props.product.stocked ?
this.props.product.name :
{this.props.product.name} ;
return (
{name} {this.props.product.price} x
);
}
}

export default ProductRow;

Leave a Reply

Your email address will not be published. Required fields are marked *

Open chat