React JS Tutorial 1

Step 1: Install GitBash & NodeJS.

Step 2: Use command npm install create-react-app -g -g is to run create-react-app command globally.

Step 3: First React App, create-react-app project-name Project name should not have capital latter. This command will create all necessary tools.

Step 4: Remove all unwanted files from src directory name with App\.

Step 5: Remove Content from index.js as well.

Example 1:

import React from 'react';
import ReactDom from 'react-dom';

class Hello extends React.Component {
	
	render() {
		return (
			<h1>Hello</h1>
		)
	}
}

class World extends React.Component {
	render(){
		return (
			<p>World</p>
		)
	}
}

class HelloWorld extends React.Component {
	render(){
		return (
			<section>
				<Hello />
				<World />
			</section>
		)
	}
}

ReactDom.render( <HelloWorld />, document.getElementById('root') );

 

Important:

  1. Whatever html we are returning in render function that is calling as a JSX, and only one tag can return in one render component. If you want to return multiple tag then you can add a single wrap for those multiple tags.
  2. In JSX self closing should be closed, In HTML it was fine without closing but in React you must need to close those self closing tags. Example: Input, br, hr etc.
<input type="text" />

3. In JSX markup you can’t use class to any tag, because class is a keyword, If you really want to use it you can use className instead of class.

Example 2: 

For use JavaScript you can use {…}, we can use only expression not If, Loop statement.

import React from 'react';
import ReactDom from 'react-dom';

class HelloWorld extends React.Component {
	get_name() {
		return 'DINESH';
	}
	render() {
		return (
			<section>
				{this.get_name()}
				{4+5}
			</section>
		)
	}
}

ReactDom.render( <HelloWorld />, document.getElementById('root') );

Example 3:

Can create a constructor using `constructor` function, but that should have a `super()` function calling statement. Constructor can be used to initialize component member variables.

import React from 'react';
import ReactDom from 'react-dom';

class HelloWorld extends React.Component {
	constructor() {
		super();
		this.name = 'DINESH CHOUHAN';
	}
	render() {
		return (
			<section>
				{this.name}
			</section>
		)
	}
}

ReactDom.render( <HelloWorld />, document.getElementById('root') );

Example 4: Props and State

import React from 'react';
import ReactDom from 'react-dom';

class TodoList extends React.Component {
	constructor() {
		super();
		this.state = {
			names : ['DINESH', 'RUSHI', 'MAHESH']
		}
	}
	render() {
		return (
			<ul>
				{ this.state.names.map(function( name ){
					return <TodoItem key={name} detail={name} />;
				})}
			</ul>
		)
	}
}

class TodoItem extends React.Component {
	constructor() {
		super();
	}
	render() {
		return (
			<li>
				{this.props.detail}
			</li>
		)
	}
}

ReactDom.render( <TodoList />, document.getElementById('root') );