Levoric Learn

Levoric Learn

Docs Frameworks Tutorials Examples Blogs

Help Center | Levoric Learn

About Us Privacy Policy Terms and Condtion

React JS Tutorials

Introduction to React JS

React JS, often simply referred to as React, is a JavaScript library for building user interfaces. Developed and maintained by Facebook, it is widely used for creating web applications with interactive and dynamic user experiences. React allows developers to build web applications that can update and render efficiently in response to data changes.

Core Concepts of React

React introduces several core concepts that are fundamental to understanding and working with the library:

    • Components: Components are the building blocks of a React application. Each component represents a part of the user interface, and they can be nested, managed, and handled independently.
    • JSX: JSX is a syntax extension for JavaScript that allows you to write HTML directly within React code. It makes the code easier to write and understand by combining the power of JavaScript with the simplicity of HTML.
    • State and Props: State and props are core concepts for managing data in React. State is used for managing local component data, while props are used to pass data from one component to another.
    • Virtual DOM: The Virtual DOM is a lightweight representation of the actual DOM. React uses the Virtual DOM to optimize rendering by updating only the parts of the DOM that have changed.

    Setting Up React

    To start working with React, you need to set up your development environment. There are several ways to do this, including using a CDN, installing via npm, or using Create React App.

  1. Using Create React App

    The easiest way to get started with React is by using Create React App, a command-line tool that sets up a new React project with a sensible default configuration. Here’s how to use it:

    Copy to clipboard
     
    npx create-react-app my-app
    cd my-app
    npm start
    
  2. Creating Your First React Component

    React components can be created as either class components or function components.

    Class Component

    Copy to clipboard
     
    import React, { Component } from 'react';
    
    class Welcome extends Component {
    render() {
    return <h1 class="ll-html-tutorials-h1">Hello, {this.props.name}</h1>;
    }
    }
    
    export default Welcome;
    
  3. Function Component

    Copy to clipboard
     
    import React from 'react';
    
    function Welcome(props) {
    return <h1 class="ll-html-tutorials-h1">Hello, {props.name}</h1>;
    }
    
    export default Welcome;
    
  4. State and Lifecycle

    State and lifecycle methods allow you to create components that can manage and respond to changes in their own data. example of a stateful component using class syntax:

    Copy to clipboard
     
    import React, { Component } from 'react';
    
    class Clock extends Component {
    constructor(props) {
    super(props);
    this.state = { date: new Date() };
    }
    
    componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
    }
    
    componentWillUnmount() {
    clearInterval(this.timerID);
    }
    
    tick() {
    this.setState({
    date: new Date()
    });
    }
    
    render() {
    return (
    <div>
    <h2 class="ll-html-tutorials-h2">It is {this.state.date.toLocaleTimeString()}.</h2>
    </div>
    );
    }
    }
    
    export default Clock;
    
  5. Handling Events

    Handling events in React is similar to handling events on DOM elements. However, there are some syntax differences:

    • React events are named using camelCase, rather than lowercase.
    • With JSX, you pass a function as the event handler, rather than a string.

    example of a button click event handler:

    Copy to clipboard
     
    import React, { Component } from 'react';
    
    class Toggle extends Component {
    constructor(props) {
    super(props);
    this.state = { isToggleOn: true };
    
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
    }
    
    handleClick() {
    this.setState(state => ({
    isToggleOn: !state.isToggleOn
    }));
    }
    
    render() {
    return (
    <button onClick={this.handleClick}>
    {this.state.isToggleOn ? 'ON' : 'OFF'}
    </button>
    );
    }
    }
    
    export default Toggle;
    
  6. Conditional Rendering

    In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them.

    Copy to clipboard
     
    function UserGreeting(props) {
    return <h1 class="ll-html-tutorials-h1">Welcome back!</h1>;
    }
    
    function GuestGreeting(props) {
    return <h1 class="ll-html-tutorials-h1">Please sign up</h1>;
    }
    
    function Greeting(props) {
    const isLoggedIn = props.isLoggedIn;
    if (isLoggedIn) {
    return <UserGreeting />;
    }
    return <GuestGreeting />;
    }
    
  7. Lists and Keys

    React allows you to build dynamic lists of elements. When rendering lists, you should always include a unique key for each element. This helps React identify which items have changed, are added, or are removed.

    Here an example of rendering a list of items:

    Copy to clipboard
     
    function ListItem(props) {
    return <li class="ll-html-tutorials-li">{props.value}</li>;
    }
    
    function NumberList(props) {
    const numbers = props.numbers;
    const listItems = numbers.map((number) =>
    <ListItem key={number.toString()} value={number} />
    );
    return (
    <ul>
    {listItems}
    </ul>
    );
    }
    
    const numbers = [1, 2, 3, 4, 5];
    ReactDOM.render(
    <NumberList numbers={numbers} />,
    document.getElementById('root')
    );
    
  8. Forms

    In React, form elements such as input, textarea, and select maintain their own state and update it based on user input. To handle forms in React, you need to add event handlers to handle changes and form submissions.

    Here an example of a controlled component:

    Copy to clipboard
     
    class NameForm extends React.Component {
    constructor(props) {
    super(props);
    this.state = { value: '' };
    
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    }
    
    handleChange(event) {
    this.setState({ value: event.target.value });
    }
    
    handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
    }
    
    render() {
    return (
    <form onSubmit={this.handleSubmit}>
    <label>
    Name:
    <input type="text" value={this.state.value} onChange={this.handleChange} />
    </label>
    <input type="submit" value="Submit" />
    </form>
    );
    }
    }
    
    ReactDOM.render(
    <NameForm />,
    document.getElementById('root')
    );
    
  9. Lifting State Up

    In React, it is common for multiple components to share state. To do this, you lift the shared state up to their closest common ancestor. This allows the ancestor component to manage the state and pass it down as props to its children.

    Here’s an example of lifting state up:

    Copy to clipboard
     
    function BoilingVerdict(props) {
    if (props.celsius >= 100) {
    return <p class="ll-html-tutorials-p">The water would boil.</p>;
    }
    return <p class="ll-html-tutorials-p">The water would not boil.</p>;
    }
    
    class Calculator extends React.Component {
    constructor(props) {
    super(props);
    this.state = { temperature: '' };
    
    this.handleChange = this.handleChange.bind(this);
    }
    
    handleChange(e) {
    this.setState({ temperature: e.target.value });
    }
    
    render() {
    const temperature = this.state.temperature;
    return (
    <fieldset>
    <legend>Enter temperature in Celsius:</legend>
    <input
    value={temperature}
    onChange={this.handleChange} />
    <BoilingVerdict
    celsius={parseFloat(temperature)} />
    </fieldset>
    );
    }
    }
    
    ReactDOM.render(
    <Calculator />,
    document.getElementById('root')
    );
    
  10. Composition vs Inheritance

    React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components. Components can accept arbitrary props, including primitive values, React elements, or functions.

    example of composition:

    Copy to clipboard
     
    function FancyBorder(props) {
    return (
    >div className={'FancyBorder FancyBorder-' + props.color}>
    {props.children}
    >/div>
    );
    }
    
    function WelcomeDialog() {
    return (
    >FancyBorder color="blue">
    >h1 class="ll-html-tutorials-h1" className="Dialog-title">
    Welcome
    >/h1>
    >p class="ll-html-tutorials-p" className="Dialog-message">
    Thank you for visiting our spacecraft!
    >/p>
    >/FancyBorder>
    );
    }
    
    ReactDOM.render(
    <WelcomeDialog />,
    document.getElementById('root')
    );
    
  11. Thinking in React

    React can change the way you think about building web applications. step-by-step guide to thinking in React:

    • Break the UI into a component hierarchy.
    • Build a static version in React.
    • Identify the minimal (but complete) representation of UI state.
    • Identify where your state should live.
    • Add inverse data flow.

Community

Stay up-to-date on the development of Levoric Learn and reach out to the community with these helpful resources.

Join Levoric Learn Community to stay ahead in your learning journey and keep up with the latest trends, insights, and developments in your field of interest. Our community is designed to foster collaboration, knowledge sharing, and continuous growth among enthusiasts, learners, and experts alike.

You can follow & Ask Question at levoriclearn @Twitter