https://devhints.io/react

 

Angular2

React

Full MVC

Handles View layer from MVC

 

Server side rendering

HTML/JS/CSS

JSX

Google

Facebook

View, Models, controllers

All about components

 A lot to code

Less to code*

 

Virtual DOM concept

 

React components are far more powerful than Angular templates; they should be compared with Angular’s directives instead. [Directives are Angular’s way of creating custom elements].

 

The virtual DOM used by React is simply an internal implementation detail of the framework which powers its amazing rendering performance.

 

React keeps two copies of a virtual DOM (the original and updated versions).



 

 

 

 

 

 

// JSX code
class Header extends React.Component {
 
render() {
   
return (
     
<h1 className='large'>Hello World</h1>
    );
  }
}

//The JSX is translated to regular JavaScript at runtime which will looks like this:
class HelloWorld extends React.Component {
 
render() {
   
return (
     
React.createElement(
       
'h1',
        {
className: 'large'},
       
'Hello World'
      )
    );
  }
}

 

 

Writing React Components Using JSX  and babel

 

 

<<script type="text/babel">
 
var Message = React.createClass({
   
render: function() {
     
return <h1>Welcome to React World</h1>
    }
  });
ReactDom.render(<Message />, document.getElementById('main'));
</script>
 

 

 

Virtual DOM: In React, Virtual DOM exists which is like a lightweight copy of the actual DOM. So for every object that exists in the original DOM there is an object for that in React Virtual DOM. It is exactly the same, but it does not have the power to directly change the layout of the document. Manipulating DOM is slow, but manipulating Virtual DOM is fast as nothing gets drawn on the screen.

 

How Virtual DOM helps React?


Each time we change something in our JSX file, all the objects that are there in the virtual DOM gets updated. Though it may sound that it is ineffective but the cost is not much significant as updating the virtual DOM doesn’t take much time. React maintains two Virtual DOM at each time, one contains the updated Virtual DOM and one which is just the pre-update version of this updated Virtual DOM. Now it compares the pre-update version with the updated Virtual DOM and figures out what exactly has changed in the DOM. This process is known as ‘diffing’. Once React finds out what exactly has changed then it updated those objects only, on real DOM. This significantly improves the performance and is the main reason why Virtual DOM is much loved by developers all around.

 

 

A Virtual DOM, used by React, is an in memory representation of the actual DOM. whereas the Shadow DOM is an HTML5 specification created to enable better composition of the DOM.

 

Shadow DOM

 

You include a third party stylesheet that includes some generic styling for table and now your calendar widgets are all broken - sounds familiar ? Congratulations - the future of the web platform has a solution for you : it is the Shadow DOM.

 

Shadow DOM was initially implemented by browser developers to implement encapsulated widgets like HTML 5 slider input element.

 

 

Components in React basically returns a piece of JSX code which tells what should be rendered on the screen. In React we mainly have two types of components:

1.     Functional Components: Functional components are simply javascript functions. We can create a functional component in React by writing a javascript function. These functions may or may not receive data as parameters:

 

function Democomponent()

{

    return <h1>Welcome Message!</h1>;

}

2.     Class Components: The class components are little more complex than the functional components. The functional components are not aware about the other components in your program where as the class components can work with each other. We can pass data from one class component to other class component. We can use javascript ES6 classes to create class based components in React. Below example shows a valid class-based component in React:

class Democomponent extends React.Component

{

    render(){

          return <h1>Welcome Message!</h1>;

    }

}

 

 

 

3 ways of sending props

 

 

 

 

 

defaultProps

 

 

 

Passing props from Parent to child

 

 

 

// Navbar Component

function Navbar() {

  return <h1>This is Navbar.</h1>

}

 

// Article list Component

function ArticleList() {

  return <h1>This is Articles List.</h1>

}

 

// App Component

function App() {

  return (

    <div>

      <Navbar />

      <ArticleList />

    </div>

  )

}

 

ReactDOM.render(<App />document.getElementById('root'))

PropTypes

// Component

class PropTypesExample extends React.Component {

  render() {

    return (

      <div>

        {/* printing all props */}

        <h1>

          {this.props.arrayProp}

          <br />

 

          {this.props.stringProp}

          <br />

 

          {this.props.numberProp}

          <br />

 

          {this.props.boolProp}

          <br />

        </h1>

      </div>

    )

  }

}

 

// validating prop types

PropTypesExample.propTypes = {

  arrayProp: PropTypes.array,

  stringProp: PropTypes.string,

  numberProp: PropTypes.number,

  boolProp: PropTypes.bool,

}

 

// creating default props

PropTypesExample.defaultProps = {

  arrayProp: ['Ram''Shyam''Raghav'],

  stringProp: 'GeeksforGeeks',

  numberProp: 10,

  boolProp: true,

}

 

export default PropTypesExample

 

 

 

ReactJS | Refs

Nice font from the url https://flaviocopes.com/react-ref-element/

 

<form ref={el => (this.form = el)}>

 

// without refs

export default class WithoutRefs extends React.Component {

  constructor() {

    super()

    this.state = { sayings: '' }

  }

  update(e) {

    this.setState({ sayings: e.target.value })

  }

  render() {

    return (

      <div>

        Mukul Says <input type='text' onChange={this.update.bind(this)} />

        <br />

        <em>{this.state.sayings}</em>

      </div>

    )

  }

}

 

When to use refs

·        Helpful when using third party libraries.

·        Helpful in animations.

When not to use refs

·        Should not be used with functional components because they dont have instances.

 

// using refs

export default class WithRefs extends React.Component {

  constructor() {

    super()

    this.state = { sayings: '' }

  }

  update() {

    this.setState({ sayings: this.refs.anything.value })

  }

  render() {

    return (

      <div>

        Mukul Says <input type='text' ref='anything' onChange={this.update.bind(this)} />

        <br />

        <em>{this.state.sayings}</em>

      </div>

    )

  }

}

 

// using callback refs

export default class CallbackRefs extends React.Component {

  constructor() {

    super()

    this.state = { sayings: '' }

  }

  update() {

    this.setState({ sayings: this.textbox.value })

  }

  render() {

    return (

      <div>

        Mukul Says{' '}

        <input

          type='text'

          ref={e => {

            this.textbox = e

          }}

          onChange={this.update.bind(this)}

        />

        <br />

        <em>{this.state.sayings}</em>

      </div>

    )

  }

}

 

 

// using without bind

export default class WithoutBind extends React.Component {

  constructor() {

    super()

    this.state = { sayings: '' }

  }

  update = () => {

    this.setState({ sayings: this.textbox.value })

  }

  render() {

    return (

      <div>

        Mukul Says{' '}

        <input

          type='text'

          ref={e => {

            this.textbox = e

          }}

          onChange={this.update}

        />

        <br />

        <em>{this.state.sayings}</em>

      </div>

    )

  }

}

 

 

 

 

 

 

 

Image result for reactjs lifecycle

 

 

 

 

Image result for reactjs lifecycle

 

 

Typical Ajax in reactjs

 

class MyComponent extends React.Component {

  constructor(props) {

    super(props)

    this.state = {

      error: null,

      isLoaded: false,

      items: [],

    }

  }

 

  componentDidMount() {

    fetch('https://api.example.com/items')

      .then(res => res.json())

      .then(

        result => {

          this.setState({

            isLoaded: true,

            items: result.items,

          })

        },

        // Note: it's important to handle errors here

        // instead of a catch() block so that we don't swallow

        // exceptions from actual bugs in components.

        error => {

          this.setState({

            isLoaded: true,

            error,

          })

        },

      )

  }

 

  render() {

    const { errorisLoadeditems } = this.state

    if (error) {

      return <div>Error: {error.message}</div>

    } else if (!isLoaded) {

      return <div>Loading...</div>

    } else {

      return (

        <ul>

          {items.map(item => (

            <li key={item.name}>

              {item.name} {item.price}

            </li>

          ))}

        </ul>

      )

    }

  }

}

 

jQuery.get in reactjs

 

 

import React from 'react';

 

export default React.createClass({

...

    componentDidMount() {

        $.get('your/url/here').done((loadedData) => {

            this.setState({data: loadedData});

    });

...

}

 

 

 

No, Babel and Webpack is not necessary for React stack. You can still find other alternatives to build your favourite stack such as Browserify and Gulp.

However, if you want to make things easier, I do recommend you learn and use Babel and Webpack together with React because:

·        You can use modules.

·        You can use JSX with ES6.

·        It support a lot of browsers

·        You can use more advanced features (async/await) etc

With webpack

·        You can use different loaders for sass, less, postcss etc

·        You can use different plugins to optimise your build such as Uglify, HotModuleReplacement, Chunks etc

 

 

 

https://blog.soshace.com/what-the-heck-is-react-hooks/?fbclid=IwAR1gr7rmss2Bp0mt1M8yOVtmWugyMiTXZsH78xQRAsSnqwOl90kxRhymdIk

 

 

No photo description available.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

https://gist.github.com/UstatleenKaur/09356f326fb008a799b6800981906bdc

// UserContext.js

 

import React from 'react';

 

const UserContext = React.createContext({}); // here we can initialise with any value we want.

 

export const UserProvider = UserContext.Provider;

export const UserConsumer = UserContext.Consumer;

export default UserContext;

 

// App.js

 

import React from 'react';

import { UserProvider } from './UserContext'

 

const App = props => {

    const user = { name: 'Ustat'age: 24 };

    

    return (

        <UserProvider value={user}>

            <div> This is App Component </div>

        </UserProvider>

    )

}

 

export default App;

 

// Providing context for both class and functional components is the same. 

// However, consuming the context is slightly different for both cases.

 

// OrderInfo

 

import React from 'react';

import { UserConsumer } from './UserContext';

 

class OrderInfo extends React.Component {

    static contextType = UserContext;

    

    componentDidMount() {

        let user = this.context;

        console.log(user); // { name: 'Ustat', age: 24 }

    }

    

    render() {

    

        // use this if you are retrieving value using contextType.

        let user = this.context;

        

        return (

            <div>{user.name}</div>

        )

        

        OR

        

        // use this if you wish to use UserConsumer

        return (

            <UserConsumer>

                {context => {

                    return <div>{context.name}</div>

                }}

            </UserConsumer>

        )

    }

}

 

// HomePage.js

 

import React, { useContext } from 'react';

import UserContext from './UserContext';

 

const HomePage = () => {

  const user = useContext(UserContext);

 

  console.log(user); // { name: 'Ustat', age: 24 }

 

  return null;

}

 

 

 

Why you should consider the new Context API in React? — A deep dive

 

How React 16 Context API Works? - Praveen Singh - Medium

 

Main API

Step 1: Initialise context

const Context = React.createContext();

Step 2: Expose it via Context.Provide

class TodoProvider extends React.Component {
  state = {todos: [...]};
  render() {
    return (
      <Context.Provider value={this.state.todos}>
        {this.props.children}
      </Context.Provider>

    );
  }
}

Step 3: Consume it via Context.Consumer

class TodoList extends React.Component {
    render() {
      return (
        <Context.Consumer>
          {todos => ....}
        </Context.Consumer>

      );
    }
  }

That’s it!

 

 

 

 


Pure Components in React are the components which do not re-renders when the value of state and props has been updated with the same values.

Features of React Pure Components

·        Prevents re-rendering of Component if props or state is the same

·        Takes care of “shouldComponentUpdate” implicitly

·        State and Props are Shallow Compared

·        Pure Components are more performant in certain cases