...

/

Incorporating the Config Component - Houses

Incorporating the Config Component - Houses

Learn how to use React Hooks in creating components in React TypeScript.

Creating the Houses component

To build the front-end app of our real estate web application—the user interface (UI)—we'll use React TypeScript components. A component is one of the core building blocks of a React TypeScript application. It is an independent, reusable snippet of code that divides the UI into smaller pieces. This allows us to break down a UI into various pieces (called components), work on them individually, and merge them into a parent component, which becomes our final UI. As such, every application we develop in React TypeScript is made up of pieces called components. Components make building UIs easier. However, each component has its structure, APIs, and methods.

To create the Houses component, we'll create a file named Houses.tsx inside the already-created config folder, which is inside the src folder of our project directory. In this file, we'll add the following lines of code:

Press + to interact
import React, { useEffect, useState } from 'react';
import Wrapper from './config/Wrapper';
import { House } from './interfaces/house';
import { Link } from 'react-router-dom';
const Houses = () => {
const [houses, setHouses] = useState([]);
useEffect(() => {
(async () => {
const response = await fetch('{{EDUCATIVE_LIVE_VM_URL}}/api/houses');
const data = await response.json();
setHouses(data);
})();
}, []);
const del = async (id: number) => {
if (window.confirm('Are you sure you want to delete this house?')) {
await fetch(`{{EDUCATIVE_LIVE_VM_URL}}/api/houses/${id}`, {
method: 'DELETE',
});
setHouses(houses.filter((h: House) => h.id !== id));
}
};
return (
<Wrapper>
<div className='pt-3 pb-2 mb-3 border-bottom'>
<div className='btn-toolbar mb-2 mb-md-0'>
<Link
to='/config/houses/create'
className='btn btn-sm btn-outline-secondary'
>
Add
</Link>
</div>
</div>
<div className='table-responsive'>
<table className='table table-striped table-sm'>
<thead>
<tr>
<th>#</th>
<th>Image</th>
<th>Name</th>
<th>Description</th>
<th>Likes</th>
<th>Checks</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{houses.map((h: House) => {
return (
<tr key={h.id}>
<td>{h.id}</td>
<td>
<img src={h.image} height='180' alt='Image' />
</td>
<td>{h.name}</td>
<td>{h.description}</td>
<td>{h.likes}</td>
<td>{h.checks}</td>
<td>
<div className='btn-group mr-2'>
<Link
to={`/config/houses/${h.id}/update`}
className='btn btn-sm btn-outline-secondary'
>
Update
</Link>
<a
href='#'
className='btn btn-sm btn-outline-secondary'
onClick={() => del(h.id)}
>
Delete
</a>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</Wrapper>
);
};
export default Houses;
  • Line 1: We import React and the two React Hooks, useEffect and useState, from react.

  • Line 2: We import the Wrapper from the config folder inside the src ...