Creating custom components
Create custom components to build modular UI building blocks, abstract functionality, and improve your project's organisation.
Components
The simplest way to define a component is to write a function that returns more components.
function HelloWorld () { return <h1 >Hello world</h1 >}
These can shorten to implicitly returning arrow functions if desired.
const HelloWorld = () => <h1 >Hello world</h1 >
Components simply return other components. Composability is the name of the game, not inheritance.
const Hello = () => <span >Hello</span >const World = () => <span >World</span > const HelloWorld = () => ( <h1 > <Hello /> <World /> </h1 >)
Components can take props:
interface GreetingsProps { name : string} const Greetings = (props : GreetingsProps ) => ( <div >Hello {props .name }! Welcome to the world.</div >)
Components are simply pure functions. Control flow is possible.
interface GreetingsProps { name : string} const Greetings = (props : GreetingsProps ) => { let greeting = 'Hello' if (props .name .length < 5) { // short names get short greetings greeting = 'Heya' } if (props .name .length < 3) { // shorter names get shorter greetings greeting = 'Hi' } return ( <div > {greeting } {props .name }! Welcome to the world. </div > )}
Using your component
You must export
your component for it to be usable outside the file you created it in.
interface GreetingsProps { name : string}export const Greetings = (props : GreetingsProps ) => ( <div >Hello {props .name }! Welcome to the world.</div >) export const SecondComponent = () => ( <div >Second component to demonstrate exporting multiple</div >) export const ThirdComponent = () => ( <div >Third component to demonstrate importing a subset of components</div >)
They can then be used elsewhere, this example shows an import from a file Otherpage.tsx
which is in the same folder as MyComponents.tsx
.
import { Greetings, SecondComponent } from './MyComponents.tsx'
const Page = () => ( <div > <Greetings name ="Tim" /> Some inline text here. <SecondComponent /> </div >)