React Props and TypeScript

type Props {
name: string
hometown: string
favoriteRestaurant?: string
}
const ContactForm= ({ name, hometown, favoriteRestaurant }: Props) => (
<>
<p>
Name: {name}
Hometown: {hometown}.
{favoriteRestaurant ?
`favoriteRestaurant: ${favoriteRestaurant}`} : null }
</p>
</>
);
Normal declaration of default props 
const ContactForm= ({ name, hometown, favoriteRestaurant = ' Alidoro' }: Props)
React's alternative to default props
ContactForm.defaultProps = {
favoriteRestaurant: 'Alidoro'
};
React.FCconst ContactForm: React.FC<Props>  = ({ name, hometown, favoriteRestaurant }) => {
return (
<>
<p>
Hello, {name}
Hometown, {hometown}
favoriteRestaurant, {favoriteRestaurant}
</p>
}
</>
);
type ContactForm {
name: string
hometown: string
}
type EventList= {
contact: ContactForm
greeting: string
vip?: boolean
renderVip?: (vip: greeting) => React.ReactNode;
}
const Greet = ({
contact,
greeting,
vip,
renderVip
}: EventList) => (
<>
<p>
Welcome, {contact.name} from {contact.hometown}
</p>
{vip ? (renderVip ? renderVip(greeting) : <p>{greeting}</p>)}
<>
);
Passing the props:
<Greet
contact={{ name: "Toby", hometown: NYC }},
vip: true,
greeting: "Thank you for you for your support"
renderVip={greeting => <h5> You are awesome!: {greeting}</h5>}
/>
Inferred State on primitive values
const [name, setName] = React.useState('Toby'); //string
const [age, setAge] = React.useState(7); //number
Defining state
const [name, setName] = React.useState<string | null> (null);
const [age, setAge] = React.useState<number | null> (7);
type ContactForm {
name: string
age: number
favoriteRestaurant?: number
}
const [form, setForm] = React.useState<ContactForm | null> (null);
Intellisense event type suggestion
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) =>
setQuery(event.currentTarget.value);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cristian Cedacero

Cristian Cedacero

Full Stack Developer — Runner — NYC