Sunday 2 July 2017

React--Components and elements

React is a JavaScript library used to build a UI. It works on the concept of components.

Components are useful to break UI down into reusable, independent pieces. It accepts inputs (props in React) and returns React elements.

Elements are the building blocks of React App which describes what should appear on screen.

Components can be defined in two ways:
As a function, also called functional because they are literally functions.
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}                                                                                 (1)
And second as class

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}                                                                                 (2)
Both (1) and (2) are same for React.



In HTML, following <div/> is present
<div id="root"></div>
which is called 'root' DOM. Everything inside it is managed by React DOM.
To render a React element into root DOM node, we need to pass both, the element and the root to ReactDOM.render()
e.g.
const element = <h1>Hello, world</h1>;
ReactDOM.render(
  element,
  document.getElementById('root')
);