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.
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
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;
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
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;