Skip to content

Instantly share code, notes, and snippets.

@chenkie
Last active Jan 19, 2021
Embed
What would you like to do?
import React, { useState } from 'react';
// types and interfaces for props
type DashboardProps = {
totalSales: number;
};
const Dashboard: React.FC<DashboardProps> = (props) => (
<section>
<p>Total Sales: {props.totalSales}</p>
</section>
);
// types applied directly to props
type Customer = {
name: string;
email: string;
};
type CustomerListProps = {
customers: Customer[];
};
const CustomerList = (props: CustomerListProps) => (
<section>
{props.customers.map((c: Customer, i: number) => (
<div key={i}>
<p>{c.name}</p>
<p>{c.email}</p>
</div>
))}
</section>
);
// event types
type DropzoneProps = {
onDragOver: React.DragEventHandler;
};
const Dropzone: React.FC<DropzoneProps> = (props) => {
return (
<div style={{ border: '2px dotted #ccc' }} onDragOver={props.onDragOver}>
<p>Welcome to the dropzone</p>
</div>
);
};
// generic passed to useState
type AccountDetails = {
username: string;
};
interface AccountSettingsProps {
accountDetails: AccountDetails;
}
const AccountSettings: React.FC<AccountSettingsProps> = (props) => {
const [accountDetails, setAccountDetails] = useState<AccountDetails>(props.accountDetails);
return (
<section>
<p>{accountDetails.username}</p>
<form>
<label>Set Username</label>
<input
placeholder="Update Username"
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setAccountDetails({
username: event.target.value
});
}}
/>
</form>
</section>
);
};
// types for children of a component.
// there's debate over which to use.
interface ContainerProps {
// children: React.ReactNode;
children: React.ReactChild;
// children: React.ReactElement;
}
const Container: React.FC<ContainerProps> = (props) => {
return <div style={{ outline: '1px solid', padding: '10px' }}>{props.children}</div>;
};
function App() {
return (
<div>
<Dashboard totalSales={10000} />
<CustomerList customers={[{ name: 'John Doe', email: 'john@doe.com' }]} />
<Dropzone onDragOver={(e) => console.log('on drag', e.clientX, e.clientY)} />
<AccountSettings
accountDetails={{
username: 'John Doe'
}}
/>
<Container>
This text works of we use React.ReactChild or
React.ReactNode, but not if we use React.ReactElement
</Container>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment