Search⌘ K
AI Features

Incorporating the Config Component HousesCreate

Explore how to create the HousesCreate component in React TypeScript to allow users to submit house details. Understand state handling with useState, form submission, and redirect logic before integrating the component into the main App using React Router DOM for seamless navigation.

Creating the HousesCreate component

To create the HousesCreate component, which enables us to create a house from the frontend of our real estate web application, we'll create a file named HousesCreate.tsx inside the already-created config folder inside the src folder of our project directory. In this file, we'll add the following lines of code:

TypeScript 4.9.5
import React, { SyntheticEvent, useState } from 'react';
import Wrapper from './config/Wrapper';
import { Redirect } from 'react-router-dom';
const HousesCreate = () => {
const [name, setName] = useState('');
const [image, setImage] = useState('');
const [description, setDescription] = useState('');
const [redirect, setRedirect] = useState(false);
const submit = async (e: SyntheticEvent) => {
e.preventDefault();
await fetch('{{EDUCATIVE_LIVE_VM_URL}}/api/houses', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
image,
description,
}),
});
setRedirect(true);
};
if (redirect) {
return <Redirect to={'/config/houses'} />;
}
return (
<Wrapper>
<form onSubmit={submit}>
<div className='form-group'>
<label>Name</label>
<input
placeholder='Name'
type='text'
className='form-control'
name='name'
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className='form-group'>
<label>Image</label>
<input
placeholder='Image'
type='text'
className='form-control'
name='image'
onChange={(e) => setImage(e.target.value)}
/>
</div>
<div className='form-group'>
<label>Description</label>
<input
placeholder='Description'
type='text'
className='form-control'
name='description'
onChange={(e) => setDescription(e.target.value)}
/>
</div>
<button className='btn btn-outline-secondary'>Save</button>
</form>
</Wrapper>
);
};
export default HousesCreate;
  • Line 1: We import React—React’s event handling system—syntheticEvent, and the React Hook useState from react.

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

  • Line 3: We import the React Router DOM’s core component, ...