How to create a component in react js
In this article, we will explain to you how to create a component in react js. Component means a specific part of code that is reuse in your code. there are two types of components. Function component and Class component. so we will know about the Function component and Class component.
so you can see the following example to create a component in react js.
Create a Function Component
The Function component is a simple component because we can not create our own state and props. it also returns only render, so it’s known as a stateless component.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 | import React from 'react'; import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="container"> <h2>Example of Function component</h2> </div> ); } export default App; |
Create a Class Component
The Class component is the same as the Function component but we can declare a class and extends the react component (React.Component), the class’s name must be uppercase.
we can create our own state and props. it’s known as a stateful component. we can easily add one component to another component.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import { Modal, Button } from 'react-bootstrap'; class App extends Component { constructor(props) { super(props); this.state = { showModal: false }; this.open = this.open.bind(this); this.close = this.close.bind(this); } open() { this.setState({showModal: true}); } close() { this.setState({showModal: false}); } render() { return ( <div className="container"> <h2>React js Bootstrap Modal Example Tutorial - XpertPhp</h2> <Button onClick={this.open}>Open Modal</Button> <Modal className="modal-container" show={this.state.showModal} onHide={this.close} animation={true}> <Modal.Header closeButton> <Modal.Title>Model Title</Modal.Title> </Modal.Header> <Modal.Body> <p>Some text in the modal body.</p> </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={this.close}> Close </Button> </Modal.Footer> </Modal> </div> ); } } export default App; |