Skip to content

Instantly share code, notes, and snippets.

@chenkie
Last active January 19, 2021 17:34
Show Gist options
  • Save chenkie/d3ce07332b6fe24902f47a9b92401e89 to your computer and use it in GitHub Desktop.
Save chenkie/d3ce07332b6fe24902f47a9b92401e89 to your computer and use it in GitHub Desktop.
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