Image

React component

  1. Developer's quick notes (Snippets)

    React.js composition

    class Toolbar extends React.Component {
        render() {
            return (
                <div style={{ background: 'cyan', padding: 10 }}>
                    {this.props.children}
                </div>
            );
        }
    }
    
    
    class App extends React.Component {
        render() {
            return (
                <div>
                    <Toolbar>
                        <h1>Hello React</h1>
                        <h2>Component composition</h2>
                    </Toolbar>
                </div>
            )
        }
    }
    

    Code Splitting

    // Toolbar.js 
    import React from 'react';
    class Toolbar extends React.Component {
        render() {
            return (
                <div style={{ background: 'cyan', padding: 10 }}>
                    {this.props.children}
                </div>
            );
        }
    }
    export default Toolbar;
    
    // App.js
    import React from 'react';
    import Toolbar from './Toolbar';
    //import MyBar from './Toolbar';
    class App extends React.Component {
        render() {
            return (
                <div>
                    <Toolbar>
                        <h1>Hello React</h1>
                        <h2>Component composition</h2>
                    </Toolbar>
                </div>
            )
        }
    }
    export default App;
    
    

    Component Style

    // Toolbar.css
    .toolbar {
        background: cyan;
        padding: 10;
    }
    
    
    // Toolbar.js 
    import React from 'react';
    import './Toolbar.css';
    
    class Toolbar extends React.Component {
        render() {
            /*
            render() {
                return (
                    <div style={{ background: 'cyan', padding: 10 }}>
                        {this.props.children}
                    </div>
                );
            }
            */
            return (
                <div className="toolbar">
                    {this.props.children}
                </div>
            );
            /*
            render() {
                let parent = 200;
                let height = 150;
    
                return (
                    <div style={{ marginBottom: parent – height,
                            border: '1px solid red' }}>
                        {this.props.children}
                    </div>
                );
            }
            */
        }
    }
    export default Toolbar;
    

    CSS in JS

    const styles = {
        toolbar: {
            marginBottom: 20,
            border: '1px solid red',
        },
        dark: {
            background: 'purple',
            color: 'white',
        }
    }
    
    render() {
        return (
            <div style={styles.toolbar, styles.dark}>
                {this.props.children}
            </div>
        );
    }
    
    

    Functional Components

    import React from 'react';
    
    function Header(props) {
        return (
            <div>
                <h1>{props.name}</h1>
            </div>
        );
    }
    /*
    const Header = props => {
        return (
            <div>
                <h1>{props.name}</h1>
            </div>
        );
    }
    */
    
    /*
    const Header = props => (
        <div>
            <h1>{props.name}</h1>
        </div>
    );
    */
    
    export default Header;
    
    const Item = props => {
        return (
            <li>
                {props.name},
                ${props.price}
            </li>
        )
    }
    /*
    const Item = ({ name, price }) => (
        <li>{name}, ${price}</li>
    )
    */
    const App = props => {
        return (
            <div>
                <ul>
                    <Item name="Apple" price="0.99" />
                    <Item name="Orange" price="0.89" />
                </ul>
            </div>
        )
    }
    

    state in Function Component

    let [ name, setName ] = React.useState('Bob');
    let [ age, setAge ] = React.useState(22);
    
    setName('Tom'); // => name = Tom
    setAge(23); // => age = 23
    
    
    
    import React, { createRef, useState } from 'react';
        const Item = ({ name, price }) => (
            <li>{name}, ${price}</li>
        )
        const App = props => {
            let [ items, setItems ] = useState([
                { id: 1, name: 'Apple', price: 0.99 },
                { id: 2, name: 'Orange', price: 0.89 },
            ]);
    
            let nameRef = createRef();
            let priceRef = createRef();
    
            let add = () => {
                let id = items.length + 1;
                let name = nameRef.current.value;
                let price = priceRef.current.value;
            }
            
            setItems([
                ...items,
                { id, name, price }
            ]);
        }
    
        return (
            <div>
                <ul>
                    {items.map(i => (
                        <Item
                            key={i.id}
                            name={i.name}
                            price={i.price}
                        />
                    ))}
                </ul>
                
                <input type="text" ref={nameRef} /><br />
                <input type="text" ref={priceRef} /><br />
                <button onClick={add}>Add</button>
            </div>
        }
    )
    export default App;
    

  2. Concept of component

    What Are React Components?

    React components are the individual building blocks that come together to create a full-fledged user interface. A component can be a button, a form, a header, or any other part of the webpage that you can think of.

    Think of components as reusable templates that you can place throughout your web application to construct a complete user experience.

    Why are Components Important in React?

    So, why are components such a big deal in React? There are a few reasons:

    Modularity and Reusability

    By breaking down your UI into components, you create a modular structure. This means you can develop, test, and maintain each piece of your app separately. Plus, once you've created a component, you can reuse it throughout your app, saving you time and effort.

    Efficiency in Development

    Components encourage a more efficient development process. You can have different team members working on different components simultaneously without stepping on each other's toes. This speeds up the development process and encourages collaboration.

    Maintainability

    Imagine you need to update the styling of a button that appears in multiple places in your app. With components, you only need to update the styling in one place, the button's component, and it will automatically reflect wherever it's used.

    Types of React Components

    There are two main types of components in React: functional components and class components.

    How to use functional components

    This is the simplest way to define components in React. They are basically JavaScript functions that take in props (input data) and return JSX (JavaScript Syntax Extension) elements.

    Here's a code example to show you how they work:

    import React from 'react'; // Imports the React library.
    
    // Define a functional component named "Button"
    const Button = () => {
      return (
        <button>
          Click Me
        </button>
      );
    };
    
    export default Button; // Exports the Button component to make it accessible.
    

    In this example, we've defined a component called Button using a JavaScript function. This component returns a button element with the text "Click Me".

    How to use class components

    These are JavaScript classes that extend the React.Component class. They use ES6 classes and provide more advanced features, such as state management and lifecycle methods.

    Here's a code example:

    import React, { Component } from 'react'; // Create class-based React components.
    
    // Class component
    class Counter extends React.Component {
      constructor(props) {
        super(props);
        this.state = { count: 0 };
      }
    
      render() {
        return (
          <div>
            <p>Count: {this.state.count}</p>
            <button onClick={() => this.setState({ count: this.state.count + 1 })}>
              Increment
            </button>
          </div>
        );
      }
    }
    
    export default Counter; // Exports the Counter component to make it accessible.
    

    In this example, the Counter is a class component that maintains a count in its state and updates it when the button is clicked.

    Functional components vs class components – when to use each

    Looking at the above two code snippets, you can differentiate them base on a few factors.

    • Syntax: functional component are less verbose and easier to read due to their concise syntax. Class components are more verbose due to the class structure and the need to bind event handlers in the constructor.
    • State: until the introduction of hooks, functional components couldn't hold State. With hooks, you can now use the useState hook to manage state in functional components. Class component can hold state using the this.state property. State updates are done using this.setState().
    • Lifecycle: functional components don't have lifecycle methods. Hooks like useEffect can be used to achieve similar effects. Class components support various Lifecycle Methods like componentDidMount, componentDidUpdate, componentWillUnmount, and so on.
    • Performance: functional components perform better as they don't need extra work required for creating classes. Class component can be a bit slower because of the extra work required for creating classes.
    • Recommended Use: functional components are preferred for most use cases in modern React development due to their simplicity and functional nature. Class components are still relevant for more complex scenarios that require state management and lifecycle methods (though hooks have made class components less necessary). React is continually evolving, and new patterns and features might emerge. Stay updated with the latest React documentation and best practices.

    How to Pass Data to Components using Props

    Props (properties) are like instructions you give to your components. They allow you to pass data from a parent component to a child component. This way, you can customize how components appear and behave.

    In simple terms, props are like the parameters that you pass to a function. You can use props to customize the content and behavior of a component based on the values you provide when you use or render that component.

    Here's a code example to show you how they work:

    // ParentComponent.js
    import React from 'react';
    import ChildComponent from './ChildComponent';
    
    const ParentComponent = () => {
      return <ChildComponent name="Cas" />;
    };
    
    export default ParentComponent;
    
    // ChildComponent.js
    import React from 'react';
    
    const ChildComponent = (props) => {
      return <p>Hello, {props.name}!</p>;
    };
    
    export default ChildComponent;
    

    In this example, the ParentComponent passes the name prop to ChildComponent, which displays a personalized greeting, Hello, Cas!.

    How to render with props

    Rendering with props allows you to create flexible and interactive user interfaces by passing and customizing data within your components. Once you have access to the data within the child component, you can use it to render dynamic content within the component's JSX. This means you can display different UI elements based on the values of the props.

    In the ParentComponent used above, you can pass different values to the name prop to customize the displayed message.

    Here's a code example:

    // ParentComponent.js
    import React from 'react';
    import ChildComponent from './ChildComponent';
    
    const ParentComponent = () => {
      return (
        <div>
          <ChildComponent name="Cas" />;
          <ChildComponent name="Nuel" />;
          <ChildComponent name="Abbey" />;
        </div>
      )
    };
    
    export default ParentComponent;
    

    In this example, different values are provided for the name prop. The displayed messages will be:

    • Hello, Cas!
    • Hello, Nuel!
    • Hello, Abbey!

    What is dynamic rendering?

    Rendering with props becomes powerful when combined with JavaScript expressions. You can use props along with other variables, functions, or logic to render dynamic content. This flexibility enables you to create versatile and interactive user interfaces.

    Here's a code example to show you how this works:

    import React from 'react';
    
    const Product = (props) => {
      return (
        <div>
          <h2>{props.name}</h2>
          <p>Price: ${props.price}</p>
          {props.isOnSale && <p>On Sale!</p>}
        </div>
      );
    };
    
    export default Product;
    

    In this example, the Product component takes multiple props to render details about a product, including its name, price, and whether it's on sale. The expression

    {props.isOnSale && <p>On Sale!</p>}
    

    conditionally renders the "On Sale!" message if the isOnSale prop is true.

    What are default props?

    In some cases, you might want to provide default values for props in case they aren't explicitly passed. This ensures your component doesn't break due to missing data.

    Here's a code example:

    const ChildComponent = (props) => {
      return <p>Hello, {props.name}!</p>;
    };
    
    ChildComponent.defaultProps = {
      name: "Guest",
    };
    

    In this example, if a value is not provided for the name property, it uses its default value of "Guest".

    How to use PropTypes

    To maintain the integrity of your application, you can specify the expected types for your props using propTypes.

    Here's a code example:

    import PropTypes from 'prop-types';
    
    ChildComponent.propTypes = {
      name: PropTypes.string.isRequired,
    };
    

    In this example, if the string is not provided for the property value, it will throw an error message.

    Other ways to declare components

    There are many ways to declare components when using React.js. There are two kinds of components, stateless components and stateful components.

    Stateful

    Class Type Components

    class Cat extends React.Component {
      constructor(props) {
        super(props);
    
        this.state = {
          humor: 'happy'
        }
      }
      render() {
        return(
          <div>
            <h1>{this.props.name}</h1>
            <p>
              {this.props.color}
            </p>
          </div>
        );
      }
    }
    

    Stateless Components

    Functional Components (Arrow Function from ES6)

    const Cat = props => {
      return (  
        <div>
          <h1>{props.name}</h1>
          <p>{props.color}</p>
        </div>;
      );
    };
    Implicit Return Components
    const Cat = props => 
      <div>
        <h1>{props.name}</h1>
        <p>{props.color}</p>
      </div>;
    

    Fragments are way to render multiple elements without using a wrapper element. When attempting to render elements without an enclosing tag in JSX, you will see the error message Adjacent JSX elements must be wrapped in an enclosing tag. This is because when JSX transpiles, it’s creating elements with their corresponding tag names, and doesn’t know what tag name to use if multiple elements are found.

    In the past, a frequent solution to this was to use a wrapper div to solve this problem. However, version 16 of React brought the addition of Fragment, which makes this no longer necessary.

    Fragment acts a wrapper without adding unnecessary divs to the DOM. You can use it directly from the React import, or deconstruct it:

    import React from 'react';
    
    class MyComponent extends React.Component {
      render(){
        return (
          <React.Fragment>
            <div>I am an element!</div>
            <button>I am another element</button>
          </React.Fragment>
        );
      }
    }
    export default MyComponent;
    
    
    
    // Deconstructed
    import React, { Component, Fragment } from 'react';
    
    class MyComponent extends Component {
      render(){
        return (
          <Fragment>
            <div>I am an element!</div>
            <button>I am another element</button>
          </Fragment>
        );
      }
    }
    
    export default MyComponent;
    

    React version 16.2 simplified this process further, allowing for empty JSX tags to be interpreted as Fragments:

    return (
      <>
        <div>I am an element!</div>
        <button>I am another element</button>
      </>
    );
    

    JSX

    JSX is short for JavaScript XML.

    JSX is an expression which uses valid HTML statements within JavaScript. You can assign this expression to a variable and use it elsewhere. You can combine other valid JavaScript expressions and JSX within these HTML statements by placing them within braces ({}). Babel further compiles JSX into an object of type React.createElement().

    Single-line & Multi-line expressions

    Single-line expression are simple to use.

    const one = <h1>Hello World!</h1>;
    

    When you need to use multiple lines in a single JSX expression, write the code within a single parenthesis.

    const two = (
      <ul>
        <li>Once</li>
        <li>Twice</li>
      </ul>
    );
    

    Using only HTML tags

    const greet = <h1>Hello World!</h1>;
    

    Combining JavaScript expression with HTML tags

    We can use JavaScript variables within braces.

    const who = "Quincy Larson";
    const greet = <h1>Hello {who}!</h1>;
    

    We can also call other JavaScript functions within braces.

    function who() {
      return "World";
    }
    const greet = <h1>Hello {who()}!</h1>;
    

    Only a single parent tag is allowed

    A JSX expression must have only one parent tag. We can add multiple tags nested within the parent element only.

    // This is valid.
    const tags = (
      <ul>
        <li>Once</li>
        <li>Twice</li>
      </ul>
    );
    
    // This is not valid.
    const tags = (
      <h1>Hello World!</h1>
      <h3>This is my special list:</h3>
      <ul>
        <li>Once</li>
        <li>Twice</li>
      </ul>
    );
    

  3. Examples of component

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
    
    const element = <Welcome name="Faisal Arkan" />;
    ReactDOM.render(
      element,
      document.getElementById('root')
    );
    

  4. Note image
    Example 2 of Component

    index.js

    import React from 'react';
    import {render} from 'react-dom';
    import './index.css';
    import App from './App';
    
    render(<App />, document.getElementById('root'));
    

    App.js

    import React, { Component } from 'react'
    // import './App.css'
    import TodoList from './TodoList'
    import TodoItems from './TodoItems'
    
    class App extends Component {
      inputElement = React.createRef()
      constructor() {
        super()
        this.state = {
          items: [],
          currentItem: {
            text: '',
            key: '',
          },
        }
      }
      deleteItem = key => {
        const filteredItems = this.state.items.filter(item => {
          return item.key !== key
        })
        this.setState({
          items: filteredItems,
        })
      }
    
      handleInput = e => {
        const itemText = e.target.value
        const currentItem = { text: itemText, key: Date.now() }
        this.setState({
          currentItem,
        })
      }
      addItem = e => {
        e.preventDefault()
        const newItem = this.state.currentItem
        if (newItem.text !== '') {
          const items = [...this.state.items, newItem]
          this.setState({
            items: items,
            currentItem: { text: '', key: '' },
          })
        }
      }
      render() {
        return (
          <div className="App">
            <TodoList
              addItem={this.addItem}
              inputElement={this.inputElement}
              handleInput={this.handleInput}
              currentItem={this.state.currentItem}
            />
            <TodoItems entries={this.state.items} deleteItem={this.deleteItem} />
          </div>
        )
      }
    }
    
    export default App
    

    TodoList.js

    import React, { Component } from 'react'
    
    class TodoList extends Component {
      componentDidUpdate() {
        this.props.inputElement.current.focus()
      }
      render() {
        return (
          <div className="todoListMain">
            <div className="header">
              <form onSubmit={this.props.addItem}>
                <input
                  placeholder="Task"
                  ref={this.props.inputElement}
                  value={this.props.currentItem.text}
                  onChange={this.props.handleInput}
                />
                <button type="submit"> Add Task </button>
              </form>
            </div>
          </div>
        )
      }
    }
    
    export default TodoList
    

    TodoItem.js

    import React, { Component } from 'react'
    
    class TodoItems extends Component {
      createTasks = item => {
        return (
          <li key={item.key} onClick={() => this.props.deleteItem(item.key)}>
            {item.text}
          </li>
        )
      }
      render() {
        const todoEntries = this.props.entries
        const listItems = todoEntries.map(this.createTasks)
    
        return <ul className="theList">{listItems}</ul>
      }
    }
    
    export default TodoItems
    

aung thu oo

#HIRE ME

OPEN TO WORK

Ko Aung Thu Oo

Having over 15 years of working experience in Laravel, PHP, Flutter, Node.Js, Vue.JS, JAVA. Strong information technology professional with a degree i...

View detail