Components are core building blocks for applications developed by React. They return React elements written in JSX. Components are stateful and help you to build dynamic & interactive UI screens.

React follows Component-driven development which means entire view is divided into components. Each component is specifically designed to do only one particular task. So all the logic required for the task is encapsulated into one component. This makes maintenance and debugging very easy.

Each component will have everything needed for displaying view like state(data), logic, event handlers (for example: button clicks, form input changes) and styles.

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation

Basic Component Example

function FirstComponent() {
    return <h4>First Example of Component !!</h4>
}
ReactDOM.render(<FirstComponent />, container1);

Let's breakdown example step by step.

  1. We created a function which returns a JSX statement.
  2. ReactDOM.render was called with element . Function is rendered as element, these kind of functions are called Functional Components, React will understand make them available as elements.

Transpiled version of above code.

function FirstComponent() {
    return <p>First Example of Component !!</p>
}
ReactDOM.render(<FirstComponent />, container1);

Component using React Class

class TestComponent extends React.Component {
    render() {
        return (<h4> Example using React Class </h4>);
    }
}
ReactDOM.render(<TestComponent />, container2);

Let's breakdown example step by step.

  1. We created a class which extends render method returned
  2. render method returned a JSX statement. This method is mandatory while creating Components using classes. Only element within render method is attached to DOM.
  3. ReactDOM.render was called with element .

Transpiled version of above code.

class TestComponent extends React.Component {
    render() {
        return (<h4> Example using React Class </h4>);
    }
}
ReactDOM.render(<TestComponent />, container2);
React Components always start with capital letter, where as DOM elements start with small letter.
Components should always return content wrapped in single element, multiple elements will give an error.
Class Components have an advantage of tapping into life-cycle and do additional stuff, whereas for Functional Components its not possible.

results matching ""

    No results matching ""