fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@@ -0,0 +1,40 @@
---
title: A React Environment Using a Remote Code Repository
---
This is how to create a non production React environment utilizing a remote code repository.
We will use the cdnjs.cloudflare.com 16.0.0 react, react-dom, and babel-standalone 6.26.0
to accomplish this.
babel-polyfill is used for older browsers compatibility.
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello React</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.min.js">
</script>
</head>
<body>
<div id="helloreact"></div>
<script type="text/babel">
ReactDOM.render(
<h1>Hello React</h1>, document.getElementById('helloreact'));
</script>
</body>
</html>
```
If this code is saved with the html file extension (helloReact.html)it can be opened in a web browser
it will run React and Babel.

View File

@@ -0,0 +1,83 @@
---
title: React - Components
---
## React - Components
Components are reusable in react.js. You can inject value into props as given below :
```jsx
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Faisal Arkan" />;
ReactDOM.render(
element,
document.getElementById('root')
);
```
The value ```name="Faisal Arkan"``` will be assigned to ```{props.name}``` from ```function Welcome(props)``` and returns a component ```<h1>Hello, Faisal Arkan</h1>``` which is saved into the const variable ```element```. The component can then be rendered via ```ReactDOM.render(element, document.getElementById('root'));```. ```document.getElementById('root')``` in this case is the target location you would like the ```element``` component to be rendered.
### Other ways to declare components
There are many ways to declare components when using React.js, but there are two kinds of components, ***stateless*** components and ***stateful*** components.
### Stateful
#### Class Type Components
```jsx
class Cat extends React.Component {
constructor(props) {
super(props);
this.state = {
humor: 'happy'
}
}
render() {
return(
<div>
<h1>{this.props.name}</h1>
<p>
{this.props.color}
</p>
</div>
);
}
}
```
### Stateless Components
#### Functional Components (Arrow Function from ES6)
```jsx
const Cat = props => {
return (
<div>
<h1>{props.name}</h1>
<p>{props.color}</p>
</div>;
);
};
```
#### Implicit Return Components
```jsx
const Cat = props =>
<div>
<h1>{props.name}</h1>
<p>{props.color}</p>
</div>;
```

View File

@@ -0,0 +1,12 @@
---
title: Components
---
# Components
Components are the building blocks of React.
### More Information:
<a href='https://reactjs.org/docs/components-and-props.html' target='_blank' rel='nofollow'>Components and Props</a>
<br />

View File

@@ -0,0 +1,60 @@
---
title: Fragments
---
# Fragments
Fragments are way to render multiple elements without using a wrapper element. When attempting to render elements without an enclosing tag in JSX, you will see the error message `Adjacent JSX elements must be wrapped in an enclosing tag`. This is because when JSX transpiles, it's creating elements with their corresponding tag names, and doesn't know what tag name to use if multiple elements are found. In the past, a frequent solution to this was to use a wrapper div to solve this problem. However, version 16 of React brought the addition of `Fragment`, which makes this no longer necessary.
`Fragment` acts a wrapper without adding unnecessary divs to the DOM. You can use it directly from the React import, or deconstruct it:
```jsx
import React from 'react';
class MyComponent extends React.Component {
render(){
return (
<React.Fragment>
<div>I am an element!</div>
<button>I am another element</button>
</React.Fragment>
);
}
}
export default MyComponent;
```
```jsx
// Deconstructed
import React, { Component, Fragment } from 'react';
class MyComponent extends Component {
render(){
return (
<Fragment>
<div>I am an element!</div>
<button>I am another element</button>
</Fragment>
);
}
}
export default MyComponent;
```
React version 16.2 simplified this process further, allowing for empty JSX tags to interpretted as Fragments:
```jsx
return (
<>
<div>I am an element!</div>
<button>I am another element</button>
</>
);
```
#### More Information:
* [React.Fragment (Official Documentation)](https://reactjs.org/docs/react-api.html#reactfragment)
* [React v16.2.0: Improved Support for Fragments](https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html)

View File

@@ -0,0 +1,68 @@
---
title: Functional Components vs Class Components
---
## Functional Components vs Class Components
There are mainly two components in React:
* Functional Components
* Class Components
## Functional Components
* Functional components are basic JavaScript functions. These are typically arrow functions but can also be created with the regular `function` keyword.
* Sometimes referred to as "dumb" or "stateless" components as they simply accept data and display them in some form; that is they are mainly responsible for rendering UI.
* React lifecycle methods (for example, `componentDidMount`) cannot be used in functional components.
* There is no render method used in functional components.
* These are mainly responsible for UI and are typically presentational only (For example, a Button component).
* Functional components can accept and use props.
* Functional components should be favored if you do not need to make use of React state.
```js
import React from "react";
const Person = props => (
<div>
<h1>Hello, {props.name}</h1>
</div>
);
export default Person;
```
## Class Components
* Class components make use of ES6 class and extend the `Component` class in React.
* Sometimes called "smart" or "stateful" components as they tend to implement logic and state.
* React lifecycle methods can be used inside class components (for example, `componentDidMount`).
* You pass props down to class components and access them with `this.props`
```js
import React, { Component } from "react";
class Person extends Component {
constructor(props){
super(props);
this.state = {
myState: true;
}
}
render() {
return (
<div>
<h1>Hello Person</h1>
</div>
);
}
}
export default Person;
```
## More Information
* [React Components](https://reactjs.org/docs/components-and-props.html)
* [Functional vs class components](https://react.christmas/16)
* [Stateful vs Stateless Functional Components in React](https://code.tutsplus.com/tutorials/stateful-vs-stateless-functional-components-in-react--cms-29541)
* [State and LifeCycle](https://reactjs.org/docs/state-and-lifecycle.html)

View File

@@ -0,0 +1,104 @@
---
title: Handling Data with Props in React
---
## Handling Data with Props in React
Props provide a way for passing and accessing data in React components.
Data is passed to React components as an attribute in JSX.
```javascript
<MyComponent someAttribute={data.value} />
```
In JSX the curly braces indicate a JavaScript expression which must return a value. The passed data is accessed via props in the defined component.
```javascript
const MyComponent = props => {
<p>{props.someAttribute}</p>
};
```
Now lets walk through an example in CodePen.
### Getting Started
If you haven't already, go ahead and sign up for a [free CodePen account](https://codepen.io/accounts/signup/user/free).
Create a new pen by selecting 'Create' > 'New Pen' next to your CodePen profile picture.
Next we'll add the appropriate libraries to render our React components.
Open your JavaScript settings pane by selecting 'Settings' > 'JavaScript'. Select 'Babel' under 'JavaScript Preprocessor'.
Next let's add our React libraries. Under 'External JavaScript' select the 'Quick-add' drop-down and add both the 'React' and 'React DOM' libraries.
### Using Props
First lets define some dummy data in our JavaScript file.
```javascript
const blogData = {
title: 'My blog title',
body: 'Arcu viverra dolor eros interdum, quis nonummy accusantium at lorem luctus iaculis.'
};
```
Next lets define our blog components.
```javascript
const Heading = () => {
return (
<h1>My Blog</h1>
);
};
const Blog = props => {
return (
<div>
<h2>{props.title}</h2>
<p>{props.body}</p>
</div>
);
};
```
Noticed how we used the props object to render the title and body values that will be passed to the Blog component. Props is read-only or immutable, so we dont have to worry about changing the props values.
Before we write our App component, we need to protect our component be defining the variable type that will passed down to each prop. We will define this using React.PropTypes. Add the following to your JavaScript file.
```javascript
Blog.propTypes = {
title: React.PropTypes.string,
body: React.PropTypes.string
};
```
Here we are defining that the the data passed down to our Blog component will be strings for both title and body. Check out [Reacts documentation](https://reactjs.org/docs/typechecking-with-proptypes.html) for a list of all propTypes.
Now lets put this together in an app component and pass down our data.
```javascript
const App = props => {
return (
<div>
<Heading />
<Blog title={blogData.title} body={blogData.body} />
<Blog title={blogData.title} body={blogData.body} />
<Blog title={blogData.title} body={blogData.body} />
</div>
);
};
```
Finally, lets render our app (be sure to add a root ```<div>``` tag to the HTML file ):
```javascript
ReactDOM.render(
<App />,
document.getElementById('root')
);
```
Now you should be seeing our blog components rendered with the dummy data passed down via props.
You can see a CodePen example [here](https://codepen.io/trey-davis/pen/MvdZGX).

View File

@@ -0,0 +1,69 @@
---
title: Hello World
---
## Hello World !!
Every language learning starts with Traditional Hello World example. Here, you get introduced to React with the same HelloWorld program.
Everything in React is a component.
But before that we need to make sure to have node.js and npm installed in the computer. Optionally we can use CRA(Create React App) which is a tool built by developers at Facebook to help you build React applications. It saves you from time-consuming setup and configuration. You simply run one command and create react app sets up the tools you need to start your React project.
We can install it through the following commands
```
npm install -g create-react-app
create-react-app my-app
cd my-app
npm start
```
The command line should give you an output where you can find the application in the browser. The default should be localhost:8080. If you are only using IE or Edge on your Windows machine, I can recommend you to install Chrome as well to access the developer environment and the React Developer Tools which are available as Chrome extension.
** If you don't use Chrome, there are extensions that let you use Chrome extensions. **
![alt react starting page](https://cdn-images-1.medium.com/max/800/1*Qcry5pCXIy2KeNRsq3w7Bg.png)
#### src/App.js
copy the code below and paste it into src/App.js
```javascript
import React from 'react';
class App extends React.Component{
constructor(props) {
super(props);
}
render(){
return(
<div>
<p>Hello World !!</p>
</div>
);
}
}
export default App;
```
If we check the index.js file in the src folder, we find that the above App.js is called into index.js and then rendered.
```javascript
// Other code
import App from './App'; // The App component is imported
// Other code
ReactDOM.render(<App />,
document.getElementById('root')); //The <App /> is the way components are called in react after importing them
// Other code
```
In the above, App.js is called a component. Normally, we make multiple components and put them together in App.js which will be then rendered in index.js which is then rendered into the root div that is in the index.html.
Congrats !! You have created your first React Hello world app. You will learn more about React in the coming articles.
Happy Coding !!

View File

@@ -0,0 +1,48 @@
---
title: Higher-Order Components
---
## Higher-Order Components
In React, a **Higher-Order Component** (HOC) is a function that takes a component and return a new component. Programmers use HOCs to achieve **component logic reuse**.
If you've used Redux's `connect`, you've already worked with Higher-Order Components.
The core idea is:
```jsx
const EnhancedComponent = enhance(WrappedComponent);
```
Where:
* `enhance` is the Higher-Order Component;
* `WrappedComponent` is the component you want to enhance; and
* `EnhancedComponent` is the new component created.
This could be the body of the `enhance` HOC:
```jsx
function enhance(WrappedComponent) {
return class extends React.Component {
render() {
const extraProp = 'This is an injected prop!';
return (
<div className="Wrapper">
<WrappedComponent
{...this.props}
extraProp={extraProp}
/>
</div>
);
}
}
}
```
In this case, `enhance` returns an **anonymous class** that extends `React.Component`. This new component is doing three simple things:
* Rendering the `WrappedComponent` within a `div` element;
* Passing its own props to the `WrappedComponent`; and
* Injecting an extra prop to the `WrappedComponent`.
HOCs are just a pattern that uses the power of React's compositional nature. **They add features to a component**. There are a lot more things you can do with them!
## Other Resources
* [React docs: Higher-Order Components](https://reactjs.org/docs/higher-order-components.html)

View File

@@ -0,0 +1,251 @@
---
title: React
---
# React
React is a JavaScript library for building user interfaces. It was voted the most loved in the "Frameworks, Libraries, and Other Technologies" category of Stack Overflow's 2017 Developer Survey.<sup>1</sup>
React is a JavaScript library and React applications built on it run in the browser, NOT on the server. Applications of this kind only communicate with the server when necessary, which makes them very fast compared to traditional websites that force the user to wait for the server to re-render entire pages and send them to the browser.
React is used for building user interfaces - what the user sees on their screen and how they interact with your web app. This interface is split up into components, instead of having one huge page you break it up into smaller pieces known as components. In more general terms, this approach is called Modularity.
- It's declarative: React uses a declarative paradigm that makes it more readable.
- It's efficient: React computes the minimal set of changes necessary to keep your DOM up-to-date.
- It's flexible: React allows the user to render one or many components to the browser.
- And it's compatible: React works well with many popular libraries and frameworks.
## Why learn React?
1. React involves Composition that is lots of components wrapping up the functionalities into an encapsulated container.
Many popular websites use React implementing the MVC architectural pattern. Facebook (Partially), Instagram (Completely), Khan Academy (Partially), Codecademy (Partially), New York Times (Partially), Yahoo Mail (Completely), Dropbox's new photo and video gallery app Carousel (Completely) are the popular websites known to be using React.
How are these large applications built using React? The simple answer is by building small applications or components.
Example:
```jsx
const Component2 = () => {
return (
<div></div>
);
};
const Component3 = () => {
return (
<div></div>
);
};
const Component1 = () => {
return (
<div>
<Component2 />
<Component3 />
</div>
);
};
ReactDOM.render(
<Component1 />,
document.getElementById("app")
);
```
2. React is Declarative for most part in which we are concerned more with What to do rather than How to do a specific task. Declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.
Declarative programming comes with certain advantages such as reduced side effects(occurs when we modify any state or mutating something or making an API request), minimizing mutability(mostly abstracted), enhanced readability, less bugs.
3. Unidirectional dataflow. UI in React is actually the function of the state that means as the state updates it updates the UI as well. So our UI progresses as the state changes.
## Advantages of React
Some reasons to use React are:
1. Fast. Apps made in React can handle complex updates and still feel quick and responsive.
2. Modular. Instead of writing large, dense files of code, you can write many smaller, reusable files. React's modularity can be a beautiful solution to JavaScript's [maintainability problems](https://en.wikipedia.org/wiki/Spaghetti_code).
3. Scalable. Large programs that display a lot of changing data are where React performs best.
4. Flexible. You can use React for interesting projects that have nothing to do with making a web app. People are still figuring out React's potential. [There's room to explore](https://medium.mybridge.co/22-amazing-open-source-react-projects-cb8230ec719f).
### Virtual DOM
React's magic comes from it's interpretation of the DOM and it's strategy for creating UIs.
React uses the virtual DOM to render an HTML tree virtually first, and then, every time a state changes and we get a new HTML tree that needs to be taken to the browsers DOM, instead of writing the whole new tree React will only write the difference between the new tree and the previous tree (since React has both trees in memory). This process is known as Tree Reconciliation.
### Reconciliation
React has a smart diffing algorithm that it uses to only regenerate in its DOM node what actually needs to be regenerated while it keeps everything else as is. This diffing process is possible because of Reacts virtual DOM.
Using the virtual DOM, React keeps the last DOM version in memory and when it has a new DOM version to take to the browser, that new DOM version will also be in memory, so React can compute the difference between the new and the old versions.
React will then instruct the browser to update only the computed diff and not the whole DOM node. No matter how many times we regenerate our interface, React will take to the browser only the new “partial” updates.
## React from Scratch
Would you like to get started learning the basics of React without getting bogged down creating a development environment?
Chances are that if you are new to web development that setting up a development environment can leave you feeling a little intimidated when you are just trying to learn React or just learn about React for the first time.
In this article we are going to look at how we can get started with React using only a text editor and a browser and nothing else.
<a href="http://www.youtube.com/watch?feature=player_embedded&v=100pKUE3OPI" target="_blank">
<img src="https://img.youtube.com/vi/100pKUE3OPI/0.jpg" alt="Watch Video Here" width="240" height="180" border="10" />
</a>
### 1Set Up Boiler Plate Code with Emmet
Lets get started with step 1. Well begin with a file in our browser called “index.html”. Well begin with the boiler plate code HTML code. For a quick start I recommend using Emmet with whatever text editor you have and on the first line typing in `html:5` then pressing the shift key to get the code below. Or you can go ahead and copy and paste the code from below.
```javascript
html:5
```
This will result in the following code:
```javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>
```
We can fill in the title of “Time to React!”.
This content will not appear in your webpage. Anything in the head section of the HTML file will be meta data that our browser will user to interpret our code in the body section. This title is going to be what appears on the tab for our page, not actually on the page.
### 2 - Get Script Tags to Harness the Power of React and Babel Libraries
Ok, item one is checked off of our list. Lets look at item two. We are going to set up our developer environment by using script tags to bring in React and Babel. This is not a real life developer environment. That would be quite an elaborate setup. It would also leave us with a lot of boiler plate code and libraries that would take us off subject of learning React basics. The goal of this series is to go over the basic syntax of React and get right into coding.
We are going to use `<script>` tags to bring in the React Library, the React DOM library (why), and the Babel library.
```javascript
<head>
...
<!-- REACT LIBRARY -->
<script src="https://unpkg.com/react@15.5.4/dist/react.js"></script>
<!-- REACT DOM LIBRARY -->
<script src="https://unpkg.com/react-dom@15.5.4/dist/react-dom.js"></script>
<!-- BABEL LIBRARY -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
...
<title>Time to React!</title>
</head>
```
You are free to use more updated versions of these libraries as they come out. They should not create any breaking changes for the content we are covering.
What are we doing here?
The: HTML `<script>` element is used to embed or reference an executable script. The “src” attribute points to the external script files for the React library, ReactDOM library and Babel library.
This is like if you have an electric razor. It is literally no good to you no matter how fancy the electric razor unless you can plug it into the wall and gain access to electricity. Our React code we will write will be no good to us if our browser cant plug into these libraries to understand and interpret what we are going.
This is how our application is going to gain the power of React, it is going to be how we insert React into the Dom. The reason that we have React and ReactDOM as two different libraries is because there are use cases such as React Native where rendering to the DOM isnt needed for mobile development so the library was split for people to make the decision for what they need depending on the project they are working on. Because we will need our React to make it to the DOM well use both scripts.
Babel is how we take advantage of ECMA script beyond ES5 and deal with something called JSX (JavaScript as XML) that we will use in React. Well take a deeper look at the magic of Babel in an upcoming lesson :)
Alright, we have completed steps 1 and 2. We have set up our boiler plate code and set up our developer environment.
### 3 - Render React to the DOM
Our next two steps will be to choose our location within DOM that we want to render our React content. And using another script tag for our React content within the body. Generally, as a good separations of concerns practice this would be in its own file then linked to this html document. Well do that later in upcoming lessons.
For now, well let this dwell within the body of the html document we are currently in.
Now we are going to look at how simple it is to choose a place on the DOM to render our React content.
Well go within the body. And best practice isnt just to throw React into the body tag to be displayed but to create a separate element, often a div, that you can treat as a root element to insert your React content.
```javascript
<body>
<div id="app">React has not rendered yet</div>
</body>
```
Well create a simple `<div>` element and give it an id of “app”. We are going to be able to target this location to insert our React content much the same way you might use CSS to target an id for styling of your choice.
Any react content will be rendered within the div tags with the id of app. In the meantime well leave some text saying that “React has not rendered yet” If we see this when we preview our page it means that somewhere we missed rendering React.
Now, lets go ahead and create a script tag within our body where we will create with react for the first time. The syntax we are going to need for our script tag is to add an attribute of “type”. This specifies the media type of the script. Above in our head we used an src attribute that pointed to the external script files for the React library, ReactDOM library and Babel library.
```javascript
<body>
<div id="app">React has not rendered yet</div>
<script type="text/babel">
</script>
</body>
```
The “type” of script that we are using well wrap in quotes and set it to `"text/babel"`.
Well need this ability to use babel right away as we work with JSX. First, we are going to render React to the DOM. We will use the `ReactDOM.render()` method to do this. This will be a method, and remember a method is just a function attached to an object. This method will take two arguments.
```javascript
<body>
<div id="app">React has not rendered yet</div>
<script type="text/babel">
ReactDOM.render(React What, React Where);
</script>
</body>
```
The first argument is the “what” of react. The second argument is the “where” of the location you want it to be placed in the DOM.
Lets start by calling our ReactDOM.render() method.
Our first argument is going to be our JSX.
```javascript
<body>
<div id="app">React has not rendered yet</div>
<script type="text/babel">
ReactDOM.render(
<h1>Hello World</h1>,
React Where
);
</script>
</body>
```
The [official react docs state](https://reactjs.org/docs/introducing-jsx.html): “This funny tag syntax is neither a string nor HTML. It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript. JSX produces React “elements”.”
Often times, JSX freaks people out who have been developers for a while because it looks like HTML. At a very early age developers are taught separation of concerns. HTML has its place, CSS has its place and JavaScript has its place. JSX seems to blur the lines. You are using what looks like HTML but as Facebook says comes with the full power of JavaScript.
This can freak out veterans so many react tutorials start without JSX which can be quite complex. We wont do that. Because this course is directed towards those who are very young in their careers you may not bring those red flags when you see this syntax.
And JSX is just really intuitive. You can probably quite easily read this code and see that this is going to be the largest header tag displaying the text “Hello World”. No mystery and pretty straightforward.
Now, lets look at what our second argument would be.
```javascript
<body>
<div id="app">React has not rendered yet</div>
<script type="text/babel">
ReactDOM.render(
<h1>Hello World</h1>,
document.getElementById("app")
);
</script>
</body>
```
This is where we want our react content rendered to the dom. Youve probably done this quite a few times in the past. Well just type in `document.getElementById()`. And well pass into the argument of the id of app. And that is it. We will now target the div with the id of app to insert our react content.
We want to make sure our content is saved. Go ahead and open this up in the browser and you should see “Hello World”. As you can probably guess, using React is not the quickest or best way to create a Hello World app. We arent quite seeing the benefits of it yet. But now, we know that everything is working.
Go ahead and open up the console and look at the “elements”. You can do that on a mac with command + shift + j or on a On Windows and Linux: Ctrl + Shift + J
If you click on the head tag we can see our script libraries we included. Then we can go down to body of our document. Lets click on our div with the id of “app”. And when we do we see our `<h1>` tag with the content “Hello World”.
[View Entire Code Here](https://github.com/robgmerrill/hello-react/blob/master/section-one/index.html)
or
<a href="http://www.youtube.com/watch?feature=player_embedded&v=100pKUE3OPI" target="_blank"><img src="http://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg"
alt="Watch Video Here" width="240" height="180" border="10" /></a>
### Recap
So lets do a quick recap. In our head tag we grabbed the script tags for React, ReactDOM and Babel. These are the tools our browser needs in its meta data to read our React code and JSX in specific.
We then located the position within the DOM that we wanted to insert our React by creating an element div with the id of “app”.
Next, we created a script tag to input our React code. We used the ReactDOM.render() method that takes two arguments. The “what” of the React content, in this case our JSX, and the second argument is the “where” that you want to insert the React content into the DOM. In this case it is the location with the id of “app”.
As an alternative to JSX, you can use ES6 and Javascript's compiler like Babel. [https://babeljs.io/](https://babeljs.io/)
### More Information:
- [React Homepage](https://reactjs.org/)
- [Dan Abramov's Twitter](https://twitter.com/dan_abramov)
- [React Tutorials at Egghead.io](https://egghead.io/browse/frameworks/react)
### Sources
1. ["Developer Survey Results 2017."](https://insights.stackoverflow.com/survey/2017#technology-most-loved-dreaded-and-wanted-frameworks-libraries-and-other-technologies) <em>Stack Overflow.</em> Accessed: October 28, 2017.

View File

@@ -0,0 +1,34 @@
---
title: Installation
---
## Installing React
### Creating a new React project
You could just embed the React library in your webpage like so<sup>2</sup>:
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/cjs/react.production.min.js"></script>
```
Smart programmers want to take the more practical and productive way: [Create React App](https://github.com/facebookincubator/create-react-app)
```bash
npm install -g create-react-app
create-react-app my-app
cd my-app
npm start
```
This will set up your development environment so that you can use the latest JavaScript features, provide a nice developer experience, and optimize your app for production.
`npm start` will start up a development server which allows live reloading<sup>3</sup>.
After you finish your project and are ready to deploy your App to production, you can just use
`npm run build`
to create an optimized build of your app in the `build`folder.
#### Usefull links
[Create React App repository](https://github.com/facebookincubator/create-react-app#create-react-app-)
#### Sources
[1. The React tutorial on installing](https://reactjs.org/docs/installation.html)
[2. Link to the React minimal JavaScript library on cdnjs.org](https://cdnjs.com/libraries/react)
[3. npm start command](https://docs.npmjs.com/cli/start)

View File

@@ -0,0 +1,107 @@
---
title: JSX
---
# JSX
> JSX is short for JavaScript XML.
JSX is an expression which uses valid HTML statements within JavaScript. You can assign this expression to a variable and use it elsewhere. You can combine other valid JavaScript expressions and JSX within these HTML statements by placing them within braces (`{}`). Babel further compiles JSX into an object of type `React.createElement()`.
### Single-line & Multi-line expressions
Single-line expression are simple to use.
```jsx
const one = <h1>Hello World!</h1>;
```
When you need to use multiple lines in a single JSX expression, write the code within a single parenthesis.
```jsx
const two = (
<ul>
<li>Once</li>
<li>Twice</li>
</ul>
);
```
### Using only HTML tags
```jsx
const greet = <h1>Hello World!</h1>;
```
### Combining JavaScript expression with HTML tags
We can use JavaScript variables within braces.
```jsx
const who = "Quincy Larson";
const greet = <h1>Hello {who}!</h1>;
```
We can also call other JavaScript functions within braces.
```jsx
function who() {
return "World";
}
const greet = <h1>Hello {who()}!</h1>;
```
### Only a single parent tag is allowed
A JSX expression must have only one parent tag. We can add multiple tags nested within the parent element only.
```jsx
// This is valid.
const tags = (
<ul>
<li>Once</li>
<li>Twice</li>
</ul>
);
// This is not valid.
const tags = (
<h1>Hello World!</h1>
<h3>This is my special list:</h3>
<ul>
<li>Once</li>
<li>Twice</li>
</ul>
);
```
### All Tags Must Be Closed
In HTML, there are self-closing tags such as `img`, `br`, `input`, and `hr`.
This means that either of these methods are valid:
```html
<!-- no closing / -->
<input type="text" name="city">
<!-- with closing / -->
<input type="text" name="city" />
```
Self-closing (sometimes referred to as **void**) tags can be rendered with or without a closing forward slash.
However, with JSX, _all_ tags must be closed.
The following JSX is invalid:
```javascript
const email = <input type="email">;
```
Closing the `input` tag will make the JSX valid:
```javascript
const email = <input type="email" />;
```
### More Information
- [Introducing JSX](https://reactjs.org/docs/introducing-jsx.html)

View File

@@ -0,0 +1,77 @@
---
title: Life Cycle Methods Of A Component
---
## Life Cycle Methods Of A Component
When we start working with components, we need to perform several actions to update state or to perform some actions when something changes in that component. In this scenario, life-cycle methods of a component comes handy !! So let us dive into them in this article.
Broadly, we can divide the life cycle methods into **3** categories.
1. Mounting
2. Updating
3. Unmounting
As life cycle methods are self explanatory, I'm just going to mention the method names. Please feel free to contribute to this article, if necessary.
## Mounting:
a. `constructor()`
b. `componentWillMount()`
c. `render()`
d. `componentDidMount()`
## Updating:
a. `componentWillRecieveProps()`
b. `shouldComponentUpdate()`
c. `componentWillUpdate()`
d. `render()`
e. `componentDidUpdate()`
## Unmounting:
a. `componentWillUnmount()`
## Some interesting facts to notice:
- `constructor`, `componentWillMount`, `componentDidMount` and `componentWillUnmount` will be called only once during the lifecycle of a component.
- `componentWillUpdate`, and `componentDidUpdate` will only be executed if and only if `shouldComponentUpdate` returns true.
- `componentWillUnmount()`will be called just before unmounting any component and hence can be used to free up the used memory, close any connections to DB, etc.
Many things can be learned by diving into coding. So get your hands dirty by coding.
Note:
> "Deprecation warnings will be enabled with a future 16.x release, **but the legacy lifecycles will continue to work until version 17.**"<sup>1</sup>
> "Even in version 17, it will still be possible to use them, but they will be aliased with an “UNSAFE_” prefix to indicate that they might cause issues. We have also prepared an [automated script to rename them](https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles) in existing code."<sup>1</sup>
In other words, these previouse lifecycles methods will still be available as:
* `UNSAFE_componentWillMount`
* `UNSAFE_componentWillReceiveProps`
* `UNSAFE_componentWillUpdate`
## New Lifecycle Methods
New lifecycle methods will be introduced in React 17
* `getDerivedStateFromProps` will be a safer alternative to `componentWillReceiveProps`.
* `getSnapshotBeforeUpdate` will be added to support safely reading properties from the DOM updates are made
Many things can be learned by diving into coding. So get your hands dirty by coding.
### Sources
1. [Vaughn, Brian. "React v16.3.0: New lifecycles and context API". March 29, 2018. Accessed: May 22, 2018.](https://reactjs.org/blog/2018/03/29/react-v-16-3.html)
### Resources
[Update on Async Rendering](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html)

View File

@@ -0,0 +1,5 @@
---
title: Props
---
### What are the props?
Props (short for properties) are the date passed into the component. They are immutable (read-only).

View File

@@ -0,0 +1,165 @@
---
title: React Props and State
---
## Props & State
There are two types of data that control a component: props and state. Props are set by the parent and they are fixed throughout the lifetime of a component. For data that is going to change, we have to use state.
### Props
Most components can be customized with different parameters when they are created. These creation parameters are called `props`.
Your own components can also use props. This lets you make a single component that is used in many different places in your app, with slightly different properties in each place. Refer to `this.props` in your render function:
```
class Welcome extends React.Component {
render() {
return <h1>Hello {this.props.name}</h1>;
}
}
const element = <Welcome name="neel" />;
```
The line `<Welcome name="neel" />` creates a property name with value `"neel"`.
the property is passed to the component, similar to how an argument is passed to a function. In fact, we could even rewrite the component to be simpler:
```
function Welcome(props) {
return <h1>Hello {props.name}</h1>;
}
```
We can make the name property optional by adding defaultProps to the Welcome class:
```
class Welcome extends React.Component {
render() {
return <h1>Hello {this.props.name}</h1>;
}
}
Welcome.defaultProps = {
name: "world",
};
```
If Welcome is called without a name it will simply render `<h1> Hello world</h1>`.
So `props` can come from the parent, or can be set by the component itself.
You used to be able to change props with setProps and replaceProps but these have been **deprecated**. During a components life cycle props should not change (consider them immutable).
Since props are passed in, and they cannot change, you can think of any React component that only uses props (and not state) as “pure,” that is, it will always render the same output given the same input. This makes them really easy to test.
### State
Like `props`, `state` holds information about the component. However, the kind of information and how it is handled is different.
By default, a component has no state. The `Welcome` component from above is stateless:
```
function Welcome(props) {
return <h1>Hello {props.name}</h1>;
}
```
When a component needs to keep track of information between renderings the component itself can create, update, and use state.
Well be working with a fairly simple component to see `state` working in action. Weve got a button that keeps track of how many times youve clicked it.
heres the code:
```
class Button extends React.Component {
constructor() {
super();
this.state = {
count: 0,
};
}
updateCount() {
this.setState((prevState, props) => {
return { count: prevState.count + 1 }
});
}
render() {
return (<button
onClick={() => this.updateCount()}
>
Clicked {this.state.count} times
</button>);
}
}
```
### state is created in the component
Lets look at the `constructor` method:
```
constructor() {
super();
this.state = {
count: 0,
};
}
```
This is where state gets its initial data. The inital data can be hard coded (as above), but it can also come from `props`.
### `state` is changeable
Heres `updateCount` method:
```
updateCount() {
this.setState((prevState, props) => {
return { count: prevState.count + 1 }
});
}
```
We change the state to keep track of the total number of clicks. The important bit is setState. First off, notice that setState takes a function, thats becuase setState can run asynchronously. It needs to take a callback function rather than updating the state directly. You can see we have access to prevState within the callback, this will contain the previous state, even if the state has already been updated somewhere else.
React goes one step better, setState updates the `state` object **and** re-renders the component automagically.
### `state` warnings
> It is tempting to write `this.state.count = this.state.count + 1`.
**Don't do this** React cannot listen to the state getting updated in this way, so your component will not re-render. Always use `setState`.
It might also be tempting to write something like this:
```
// DO NOT USE
this.setState({
count: this.state.count + 1
});
```
Although this might look reasonable, doesnt throw errors, and you might find examples that use this syntax online, it is wrong. This does not take into account the asychronous nature that `setState` can use and might cause errors with out of sync state data.
### Program Continue !!!
And finally, `render`
```
render() {
return (<button
onClick={() => this.updateCount()}
>
Clicked {this.state.count} times
</button>);
}
```
`onClick={() => this.updateCount()}` means that when the button is clicked the updateCount method will be called. We need to use **ES6s arrow function** so updateCount will have access to this instances state.
The text rendered in the button is `Clicked {this.state.count} times`, which will use whatever this.state.count is at the time of rendering.
More Info about: <a href='https://facebook.github.io/react-vr/docs/components-props-and-state.html' target='_blank' rel='nofollow'>**React props and state**</a>

View File

@@ -0,0 +1,44 @@
# React Router for beginners
# Installation
React Router has been broken into three packages: `react-router`, `react-router-dom`, and `react-router-native`.
You should almost never have to install react-router directly. That package provides the core routing components and functions for React Router applications. The other two provide environment specific (browser and react-native) components, but they both also re-export all of react-router's exports.
We are building a website (something that will be run in browsers), so we will install react-router-dom.
`npm install --save react-router-dom`
# The Router
When starting a new project, you need to determine which type of router to use. For browser based projects, there are <BrowserRouter> and <HashRouter> components. The `<BrowserRouter>` should be used when you have a server that will handle dynamic requests (knows how to respond to any possible URI), while the <HashRouter> should be used for static websites (where the server can only respond to requests for files that it knows about).
Usually it is preferable to use a `<BrowserRouter>`, but if your website will be hosted on a server that only serves static files, then the `<HashRouter>` is a good solution.
For our project, we will assume that the website will be backed by a dynamic server, so our router component of choice is the `<BrowserRouter>`.
# Import Statement
```javascript
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
```
## IndexRoute and Links
Now, lets add navigation to get us between pages.
To do this, we will be using the `<Link>` component. `<Link>` is similar to using an html anchor tag.
From the docs:
The primary way to allow users to navigate around your application. <Link> will render a fully accessible anchor tag with the proper href.
To do this, lets first create a Nav component. Our Nav component will contain `<Link>` components, and will look like this:
```javascript
const Nav = () => (
<div>
<Link to='/'>Home</Link>&nbsp;
<Link to='/address'>Address</Link>
</div>
)
```

View File

@@ -0,0 +1,58 @@
---
title: Render Props Component
---
## Render Props Component
Render props is an advanced React pattern, yet so simple!
### Example
This is an example on how you can use render prop for a toggle functionality.
```jsx
import React, { PureComponent } from "react";
class Toggle extends PureComponent {
state = {
on: false
};
toggle = () => {
this.setState({
on: !this.state.on
});
};
render() {
const { children } = this.props;
return children({
on: this.state.on,
toggle: this.toggle
});
}
}
export default Toggle;
```
This Toggle component will return it's children `state.on` and the function toggle. Which can be used in it's child components.
This Toggle can be used as follows:
```jsx
<Toggle>
{({ on, toggle }) => (
<Fragment>
<button onClick={toggle}>Show / Hide</button>
{on && <h1>I can be toggled on or off!</h1>}
</Fragment>
)}
</Toggle>
```
As you can see, the toggle functionality can be used by it's child Button to toggle some content. if on is true the h1-tag will get rendered otherwise not.
## Other Resources
* [React docs: Render props](https://reactjs.org/docs/render-props.html)

View File

@@ -0,0 +1,85 @@
---
title: State vs Props
---
## State vs Props
When we start working with React components, we frequently hear two terms. They are `state` and `props`. So, in this article we will explore what are those and how they differ.
## State:
* State is something that a component owns. It belongs to that particular component where it is defined.
For example, A person's age is a state of that person.
* State is mutable. But it can be changed by only by that component that owns it. As I only can change my age, not anyone else.
* You can change a state by using `this.setState()`
See the below example to get an idea of state:
#### Person.js
```javascript
import React from 'react';
class Person extends React.Component{
constructor(props) {
super(props);
this.state = {
age:0
this.incrementAge = this.incrementAge.bind(this)
}
incrementAge(){
this.setState({
age:this.state.age + 1;
});
}
render(){
return(
<div>
<label>My age is: {this.state.age}</label>
<button onClick={this.incrementAge}>Grow me older !!<button>
</div>
);
}
}
export default Person;
```
In the above example, `age` is the state of `Person` component.
## Props:
* Props are similar to method arguments. They are passed to a component where that component is used.
* Props is immutable. They are read-only.
See the below example to get an idea of Props:
#### Person.js
```javascript
import React from 'react';
class Person extends React.Component{
render(){
return(
<div>
<label>I am a {this.props.character} person.</label>
</div>
);
}
}
export default Person;
const person = <Person character = "good"></Person>
```
In the above example, `const person = <Person character = "good"></Person>` we are passing `character = "good"` prop to `Person` component.
It gives output as "I am a good person", in fact I am.
There is lot more to learn on State and Props. Many things can be learnt by actually diving into coding. So get your hands dirty by coding.
Reach me out on [twitter](https://twitter.com/getifyJr) if needed.
Happy Coding !!!

View File

@@ -0,0 +1,104 @@
---
title: State
---
# State
State is the place where the data comes from.
We should always try to make our state as simple as possible and minimize the number of stateful components. If we have, for example, ten components that need data from the state, we should create one container component that will keep the state for all of them.
State is basically like a global object that is available everywhere in a component.
Example of a Stateful Class Component:
```javascript
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
// We declare the state as shown below
this.state = {
x: "This is x from state",
y: "This is y from state"
}
}
render() {
return (
<div>
<h1>{this.state.x}</h1>
<h2>{this.state.y}</h2>
</div>
);
}
}
export default App;
```
Another Example:
```javascript
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
// We declare the state as shown below
this.state = {
x: "This is x from state",
y: "This is y from state"
}
}
render() {
let x1 = this.state.x;
let y1 = this.state.y;
return (
<div>
<h1>{x1}</h1>
<h2>{y1}</h2>
</div>
);
}
}
export default App;
```
## Updating State
You can change the data stored in the state of your application using the `setState` method on your component.
```js
this.setState({value: 1});
```
Keep in mind that `setState` may be asynchronous so you should be careful when using the current state to set a new state. A good example of this would be if you want to increment a value in your state.
#### The Wrong Way
```js
this.setState({value: this.state.value + 1});
```
This can lead to unexpected behavior in your app if the code above is called multiple times in the same update cycle. To avoid this you can pass an updater callback function to `setState` instead of an object.
#### The Right Way
```js
this.setState(prevState => ({value: prevState.value + 1}));
```
#### The Cleaner Way
```
this.setState(({ value }) => ({ value: value + 1 }));
```
When only a limited number of fields in the state object is required, object destructing can be used for cleaner code.
#### More Information
- [React - State and Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html)
- [React - Lifting State Up](https://reactjs.org/docs/lifting-state-up.html)
- [React Native - State Up](https://facebook.github.io/react-native/docs/state.html)

View File

@@ -0,0 +1,124 @@
---
title: React TypeChecking with PropTypes
---
## React PropTypes
These serve as a method of typechecking as an application tends go grow, with this a very big base of bugs tends to be corrected with the use of this feature.
## How to get PropTypes
Starting with React version 15.5 this feature was moved to a separate package named prop-types.
In order to use it, it's required to be added to the project as a dependency by issuing the following command in a console.
```sh
npm install --save prop-types
```
After that a whole range of validators that can be used to make sure the data the developer is going to recieve is actually valid.
When an invalid value is provided there will be warning appearing in the JavaScript console.
Note that for performance reasons the PropTypes defined are only checked while in development mode.
Also on the contrary of the component state, that can be manipulated as needed, these props are readonly.
It's value cannot be changed by the component.
## Proptypes available
Bellow is a code example with the different validators provided by the package, and how to inject them in the component.
```javascript
import PropTypes from 'prop-types';
class MyComponent extends Component{
constructor(props){
super(props);
}
render(){
return (
...
);
}
}
MyComponent.propTypes = {
// A prop that is a specific JS primitive. By default, these
// are all optional.
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: PropTypes.node,
// A React element as a PropType
optionalElement: PropTypes.element,
// Declaring that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: PropTypes.instanceOf(AnotherComponent),
// You can ensure that your prop is limited to specific values by treating
// it as an enum.
optionalEnum: PropTypes.oneOf(['News', 'Photos']),
// An object that could be one of many types
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(AnotherComponent)
]),
// An array of a certain type
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
// An object with property values of a certain type
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
// An object taking on a particular shape
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
}),
// You can chain any of the above with `isRequired` to make sure a warning
// is shown if the prop isn't provided.
requiredFunc: PropTypes.func.isRequired,
// A value of any data type
requiredAny: PropTypes.any.isRequired,
};
```
## Setting default values
As a part of this feature it's also possible to define default values for any given component defined while developing.
These make sure that the prop will have a value even if not specified by the parent component.
The code bellow ilustrates how to use this funcionality.
```javascript
import React,{Component} from 'react';
import PropTypes from 'prop-types';
class MyComponent extends Component{
constructor(props){
super(props);
}
render(){
return (
<h3>Hello, {this.props.name}</h3>
);
}
}
MyComponent.defaultProps = {
name: 'Stranger'
};
```
For more information about PropTypes and other docs on React.
Go to the [Official Site](https://reactjs.org/) and read the docs, or the [Github Repo](https://github.com/facebook/react/)

View File

@@ -0,0 +1,25 @@
---
title: Why React
---
## Why React.js?
### Simplicity
React.js is not a full fledged Javascript framework like Angular.js or other popular frontend frameworks. Instead, React.js is a JavaScript library that acts as the 'V' in MVC (Model View Controller). It is simply a view engine that can be dropped in and used with a plethora of other tools for the data and model part of MVC (most popularly Redux and Node.js).
### Performance
Since React makes use of a _Virtual DOM_, it can selectively update portions of the page as needed rather than always having to complete an entire page reload. In many cases, not updating the entire DOM will save considerably on performance. Moreover, many of the built-in functions (such as Lifecycle functions) also have performance benefits as they often help to check if a re-render is even needed to begin with.
### Low learning curve
Of the major frontend "frameworks" available, React has a relatively low barrier to entry and has a quick ramp up time. In addition, React's official documentation is extremely clear and provide many examples for most of the common use cases.
### Tooling
The tools and software commonly utilized with React are incredibly well maintained and supported and provide several different avenues of best practices to follow when developing web applications. Some of these tools include Redux, React-router, Thunk, and many others. There are also a number of development tools, such as a React and Redux Chrome extension, which helps with debugging your React applications.
### Support
React is created and maintained by the folks at Facebook and is used by individuals and companies all over the world in large volume. This means React is constantly improving and any problems you may have have probably already been asked on Stack Overflow.
Other than the above, we can take our react knowledge to develop mobile native applications using react-native and also take our knowledge and expand it to VR using react-vr. Basically learning react opens us up to various other oppurtunities like using it for Web, VR, PWA(Progressive Web App) and many others
#### More Information
To learn more about why React is so great check out the [official website](https://reactjs.org/)

View File

@@ -0,0 +1,68 @@
---
title: Your first React App
---
## Your first React App
### Installation
As specified in the previous artice (Installation), run the `Create React App` tool. After everything has finished, `cd` into the folder of your application and run `npm start`.
This will start a development server and you are all set to start developing your app!
```bash
npm install -g react-create-app
create-react-app my-first-app
cd my-first-app
npm start
```
### Editing the code
Start up your editor or IDE of choice and edit the `App.js` file in the `src` folder. When created with the `react-create-app` tool, there will already be some code in this file.
The code will consist of these parts:
#### imports
```JavaScript
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
```
This is used by [webpack](https://webpack.js.org/) to import all required modules so that your code can use them. This code imports 3 modules:
1) `React` and `Component`, which allow us to use React as it should be used. (With components)
2) `logo`, which allows us to use `logo.svg` in this file.
3) `./App.css`, which imports the stylesheet for this file.
#### classes/components
```JavaScript
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
```
React is a library that makes use of Components, which let you split up your UI into independent, reusable pieces, and think about each piece in isolation.
There is already 1 component created, the `App` component. If you used the `create-react-app` tool, this component is the main component in the project and you should build around this central class.
We will look at components more detailed in next chapters.
#### exports
When creating a class in react, you should export them after declaration, which allows you to use the component in another file by using the `import` keyword. You can use `default` after the `export` keyword to tell React that this is the main class of this file.
```JavaScript
export default App;
```
### View the results!
When you've started the development server by issuing the `npm start` command, you can view the changes you add to your project live in your browser. After issuing the command, npm should open a browser automatically displaying your app.
### Sources
[1. React documentation](https://reactjs.org/docs/hello-world.html)