...
/Incorporating the Config Component HousesUpdate
Incorporating the Config Component HousesUpdate
Learn how to use React Hooks, props, and event handlers to update components in React TypeScript.
We'll cover the following...
Creating the HousesUpdate
component
To create the HousesUpdate
component that will enable us to update a house from the frontend of our real estate web application, we'll create a file named HousesUpdate.tsx
inside the already-created config
folder of the src
folder of our project directory. In this file, we'll add the following lines of code:
Press + to interact
import React, {PropsWithRef,SyntheticEvent,useEffect,useState,} from 'react';import Wrapper from './config/Wrapper';import { Redirect } from 'react-router-dom';import { House } from './interfaces/house';const HousesUpdate = (props: PropsWithRef<any>) => {const [name, setName] = useState('');const [image, setImage] = useState('');const [description, setDescription] = useState('');const [redirect, setRedirect] = useState(false);useEffect(() => {(async () => {const response = await fetch(`{{EDUCATIVE_LIVE_VM_URL}}/api/houses/${props.match.params.id}`);const house: House = await response.json();setName(house.name);setImage(house.image);setDescription(house.description);})();}, []);const submit = async (e: SyntheticEvent) => {e.preventDefault();await fetch(`{{EDUCATIVE_LIVE_VM_URL}}/api/houses/${props.match.params.id}`, {method: 'PUT',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><inputplaceholder='Name'type='text'className='form-control'name='name'defaultValue={name}onChange={(e) => setName(e.target.value)}/></div><div className='form-group'><label>Image</label><inputplaceholder='Name'type='text'className='form-control'name='image'defaultValue={image}onChange={(e) => setImage(e.target.value)}/></div><div className='form-group'><label>Description</label><inputplaceholder='Description'type='text'className='form-control'name='description'defaultValue={description}onChange={(e) => setDescription(e.target.value)}/></div><button className='btn btn-outline-secondary'>Save</button></form></Wrapper>);};export default HousesUpdate;
Lines 1–6: We import
React
,PropsWithRef
,syntheticEvent
,useEffect
, anduseState
fromreact
.Line 7: We import the
Wrapper
from theconfig
folder in thesrc
folder. ...