Introduction To React

React or ReactJS is a front-end JavaScript library to create and design user interfaces. It’s being used in many popular and powerful websites like Facebook, PayPal, Airbnb, Apple, Microsoft, Twitter, etc. In this blog post, we discussed what’s React and what are its foundational concepts and features.

Prerequisites To Learning React

  • HTML
  • CSS
  • JavaScript
  • ECMAScript 6 or ES6 (optional)

What Is React?

  • JavaScript Library (open source)
  • Built and maintained by Facebook
  • Mostly used to develop large scale single-page applications
  • Used by many enterprise applications like PayPal, Apple, Microsoft, Twitter, Facebook, etc.

Adding React in HTML Page

We need to include two JavaScript files along with a div having id as “root” in an HTML page to get started with React. The following code can be used as a reference.

<!DOCTYPE html>
<html>
<head>
   <title>React App</title>
   <script src="https://unpkg.com/react@16.7.0/umd/react.development.js"></script>
   <script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"></script>
</head>
<body>
   <div id="root"></div>
</body>
</html>

React Developer Tools

React Elements

To add code related to the React app, create a new script tag below the div with id “root” and all React related code will reside inside that script tag.

....
<div id="root"></div>
<script type="text/javascript">
//add your code here
</script>
....

Following code can be used to create a react element

ReactDOM.render(
        //first input argument is tag name, second is for properties and third is for child elements
        React.createElement('h1', {"style": {"color": "red"}}, "Hello World!"),
        document.getElementById('root') // this tells the app to display h1 tag inside the div with id "root"
); 

Following code can be used to render multiple react elements

ReactDOM.render(
        React.createElement(
            'div',
            null, 
            React.createElement(
                'h1',
                null,
                "Hello World!"
            )
        ),
        document.getElementById('root')
); 

Using JSX

JSX or JavaScript as XML is a language extension that can be used to directly add tags inside the JavaScript code. Following JSX code will output the same as the above code.

ReactDOM.render(
        <div>
            <h1>Hello World</h1>    
        </div>,
        document.getElementById('root') 
); 

Running the above code in the browser will give an error in the console because the browser doesn’t understand that JSX syntax. To fix this we need to include another JavaScript library called “babel” below the react libraries inside the head tag and change the type of react app script from “text/javascript” to “text/babel” as follows:

....
<script src="https://unpkg.com/react@16.7.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
....
<div id="root"></div>
<script type="text/babel">
    ReactDOM.render(
        <div>
            <h1>Hello World</h1>    
        </div>,
        document.getElementById('root')
    ); 
</script>

More JSX Features

The following code describes the syntax to add class, ID or variables inside the JSX syntax.

<script type="text/babel">
    let city = "Islamabad";
    ReactDOM.render(
        <div id="myID" className="myClass">
            <h1>Hello {city}</h1>    
        </div>
        ,
        document.getElementById('root')
    ); 
</script>

React Components

  • In React UI elements are represented with the components
  • Components are used to create small repeatable UI features
  • Components are the functions to return UI elements

The above code can be refactored to use a component function for rendering HTML tags as follows:

<div id="root"></div>
   <script type="text/babel">
    const Hello = () => {
        return (
            <div id="myID" className="myClass">
                <h1>Hello World</h1>    
            </div>
        )
    };
    ReactDOM.render(
        <Hello />
        ,
        document.getElementById('root')
    ); 
</script>

React Props

  • In React, props object contains the properties of the component
  • Used to display dynamic data inside the component

Following is an example of how to use props object to pass dynamic data to components

<script type="text/babel">
    const Hello = (props) => {
        return (
            <div id="myID" className="myClass">
                <h1>Hello {props.library}</h1>
                <p>{props.message}</p>    
            </div>
        )
    };
    ReactDOM.render(
        <Hello library="ReactJS" message="Front-end library to create user interfaces"/>
        ,
        document.getElementById('root')
    ); 
</script>

Nesting Components

Following code, snippet shows how to nest components inside other components.

<script type="text/babel">
    const Project = (props) => {
        return (
            <h1>{props.name}</h1>
        );
    }
    const App = () => {
        return (
            <div>
                <Project name="SEO Headlines"/>
                <Project name="Post Columns"/>
                <Project name="Video Lightbox"/>
            </div>
        );
    }
    ReactDOM.render(
        <App />
        ,
        document.getElementById('root')
    ); 
</script>

Class Components

Following code snippet, shows how to use class components in React

<script type="text/babel">
    const Project = (props) => {
        return (
            <h1>{props.name}</h1>
        );
    }
    class App extends React.Component {
        render(){
            return (
                <div>
                    <Project name="SEO Headlines"/>
                    <Project name="Post Columns"/>
                    <Project name="Video Lightbox"/>
                </div>
            )
        }
    }
    ReactDOM.render(
        <App />
        ,
        document.getElementById('root')
    ); 
</script>

React State

  • When state data of the component is changed, the render function of the component is called again
  • State data values can be changed using events

Following is a simple representation of how the state works in a react component.

<script type="text/babel">
    const Project = (props) => {
        return (
            <h1>{props.name}</h1>
        );
    }
    class App extends React.Component {
        state = {
            loggedIn: true
        }
        render(){
            return (
                <div>
                    <div>The user is {this.state.loggedIn ? 'logged in': 'logged out'}</div>
                    <Project name="SEO Headlines"/>
                    <Project name="Post Columns"/>
                    <Project name="Video Lightbox"/>
                </div>
            )
        }
    }
    ReactDOM.render(
        <App />
        ,
        document.getElementById('root')
    ); 
</script>

React Events

React events can be used to change the state values of a component as shown in the following code snippet.

<script type="text/babel">
    const Project = (props) => {
        return (
            <h1>{props.name}</h1>
        );
    }
    class App extends React.Component {
        state = {
            loggedIn: false
        }
        logIn = () => {
            this.setState({loggedIn: true});
        }
        logOut = () => {
            this.setState({loggedIn: false});
        }
        render(){
            return (
                <div>
                    <button onClick={this.logIn}>Log In</button>
                    <button onClick={this.logOut}>Log Out</button>
                    <div>The user is {this.state.loggedIn ? 'logged in': 'logged out'}</div>
                    <Project name="SEO Headlines"/>
                    <Project name="Post Columns"/>
                    <Project name="Video Lightbox"/>
                </div>
            )
        }
    }
    ReactDOM.render(
        <App />
        ,
        document.getElementById('root')
    ); 
</script>

Conditional Rendering of React Components

The following code snippet shows how to render components based on some condition. We will render login and logout buttons based on the current login state value.

<script type="text/babel">
    const Project = (props) => {
        return (
            <h1>{props.name}</h1>
        );
    }
    class App extends React.Component {
        state = {
            loggedIn: false
        }
        logIn = () => {
            this.setState({loggedIn: true});
        }
        logOut = () => {
            this.setState({loggedIn: false});
        }
        render(){
            return (
                <div>
                    {
                        this.state.loggedIn ? <button onClick={this.logOut}>Log Out</button> : <button onClick={this.logIn}>Log In</button>
                    }
                    <div>The user is {this.state.loggedIn ? 'logged in': 'logged out'}</div>
                    <Project name="SEO Headlines"/>
                    <Project name="Post Columns"/>
                    <Project name="Video Lightbox"/>
                </div>
            )
        }
    }
    ReactDOM.render(
        <App />
        ,
        document.getElementById('root')
    ); 
</script>

Render Components Based on Array/List

The following code snippet demonstrated how to render components based on the items in an array.

<script type="text/babel">
    const todoList = [
        "Task 1", 
        "Task 2", 
        "Task 3"
    ];
    const App = ({list}) => {
        
        return (
            <ul>
                {
                    list.map(
                        (item, index) => {
                            return (
                                <li key={index}>{item}</li>
                            )
                        }
                    )
                }
            </ul>
        )
    };
    ReactDOM.render(
        <App list={todoList}/>
        ,
        document.getElementById('root')
    ); 
</script>

Render Components From List of Objects

The following example code shows how to render components from list of objects.

<script type="text/babel">
    const todoList = [
        {id: 1, name: "Task 1", sDate: "23/3/2020", eDate: "29/3/2020"}, 
        {id: 2, name: "Task 2", sDate: "23/3/2020", eDate: "29/3/2020"},
        {id: 3, name: "Task 3", sDate: "23/3/2020", eDate: "29/3/2020"},
    ];
    const App = ({list}) => {
        
        return (
            <ul>
                {
                    list.map(
                        (item) => {
                            return (
                                <li key={item.id}>{item.name} | {item.sDate}-{item.eDate}</li>
                            )
                        }
                    )
                }
            </ul>
        )
    };
    ReactDOM.render(
        <App list={todoList}/>
        ,
        document.getElementById('root')
    ); 
</script>

React Tools

Visit the blog post to learn about the commands to create a new React project using the command lines

References:

Leave a Comment

Your email address will not be published. Required fields are marked *