a blog for those who code

Saturday 25 August 2018

Getting Started With React.js

Before Getting Started with React, lets go through the StackOverflow's Developer poll where React is #2 on the Most Loved, Dreaded and Wanted Frameworks, Libraries and Tools. This shows how popular React is.

PC : StackOverflow

Some of the reasons why React is popular is because it solves real problem which front-end developers often complain like solving how to write HTML codes, with JSX and React HTML templating is just a piece of cake. Breaking the whole application into Components is one of the main feature of React. When we have started functional programming, we have been asked to keep our function small and up-to the point which does single thing, it is true with Component which also has the similar concept.

To summarise the importance of React is Easy Integration, Vast Community, JSX for HTML templating, Unidirectional Flow, React Native for Mobile Apps. Now lets get started with React.

My First React HTML Page


To get started with React we will be writing an HTML file and then render a H1 tag on the HTML page using React DOM. React DOM is responsible of rendering anything and everything to our HTML page. Inside ReactDOM.render we will be using React.createElement which creates and returns a new React Element of h1 type and the text. Next is to bind that to the existing div.

React elements are plain objects just like h1 tag and ReactDOM takes care of updating the existing DOM to match with those of REACT elements.

<!DOCTYPE html>
<html>
<head>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <title>My 1st React Page</title>
</head>
<body>
  <div id="react-div"></div>
  <script type="text/javascript">	
    ReactDOM.render(
      React.createElement('h1', null, 'I am excited to Get Started with React'),
      document.getElementById('react-div')
    )
  </script>
</body>
</html>

Getting to know About JSX


JSX is a syntax extension to JavaScript which produces the React "elements". So we can just remove the React.createElement and add a JSX equivalent for it as shown below

<h1>I am excited to Get Started with React</h1>

But if you just remove React.createElement and add the below line, it will throw an error why because browser cannot read JSX for that we have to compile JSX into JavaScript using Babel which will run in the browser. Internally Bable complies JSX down to React.createElement(). So first we will add a script <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script> just below ReactDOM and then change the render script as shown below

<script type="text/babel">	
  ReactDOM.render(
    <h1>I am excited to Get Started with React</h1>,
    document.getElementById('react-div')
  )
</script>

The good thing about JSX is that we can put any valid JavaScript expression inside the curly braces as shown below :

const name = 'I am excited to Get Started with React'
const element = <h1>{name}</h1>

ReactDOM.render(
  element,
  document.getElementById('react-div')
)

Getting to know About Components


Components are small independent and resuable pieces of the UI which can be put together to create entire user interface. Think Components as a JavaScript function which takes an input and then return JSX which should be displayed on the screen. Lets see a sample Component which displays "I am excited to Get Started with React" on the screen when called.

class Message extends React.Component {
  render() {
    return (
	<h1>I am excited to Get Started with React</h1>
    )
  }
}

In the above code we are using ES6 class component to create the React Component where we are extending it from React.Component. render() function is a required method in React Component. So this simple Component is just returning a JSX which can be called using ReactDOM.render method as shown below :

ReactDOM.render(
  <Message />,
  document.getElementById('react-div')
)

Let's Talk about Props/Properties


When you want to have an immutable data in your component, you can add it as a props and use it inside the component. The props or properties are single values or objects that are passed to the React components on the creation. The props can be used via this.props.propertyName as shown below

ReactDOM.render(
  <Message myMessage="I am excited to Get Started with React"/>,
  document.getElementById('react-div')
)

class Message extends React.Component {
  render() {
    return (
	<h1>{this.props.myMessage}</h1>
    )
  }
}

In the above code we are passing myMessage property to the class Message which will get attached to the native props object. So to access the props inside the actual React component we will be writing this.props.myMessage.

Let's Talk About State

State is one of the important React components. When a component's state data changes, the component's render function is called again to re-render the change in the state. State is very similar to props, but state is a private property of a component and its fully controlled by the component. Let's take an example

class RadioGroup extends React.Component{
 constructor(props){
  super(props);
  this.radioItemChanged = this.radioItemChanged.bind(this);
  this.state = { selectedOption: '' }
 }

 radioItemChanged(id){
  console.log('Selected Option-------' + id);
  this.setState({ selectedOption: id});
 }

 render() {
  return (<div>
    <input type="radio" name="radio" checked={this.state.selectedOption === 1} onChange={()=>this.radioItemChanged(1)}></input>
    <input type="radio" name="radio" checked={this.state.selectedOption === 2} onChange={()=>this.radioItemChanged(2)}></input>
    <input type="radio" name="radio" checked={this.state.selectedOption === 3} onChange={()=>this.radioItemChanged(3)}></input>
  </div>);
 }	
}

ReactDOM.render(
  <RadioGroup />,
  document.getElementById('react-container')
)

In the above example I have added a state in the constructor which is responsible of starting our state. selectedOption is my state variable. In this variable we can give any value as the starting value, that means if my component is rendered the initial value of the selectedOption will be blank. We also have written a custom function raioItemChanged which will handle the change of teh radio buttons and change value of the selectedOption as per the radio button selected.

Note : You have to bind radioItemChanged function in the constructor to keep 'this' in scope.

So that's it for the initial Getting Started with React, if you have any questions feel free to ask. Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a Comment