Learn how to create client-side apps using React and TypeScript
children propimport React, { useState } from "react";
import ReactDOM from "react-dom/client";
function Counter() {
// Calling the `setCount` with a new value re-runs your component
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
// Any properties passed to the component are available on the `props` object
function Title(props: { id: string; children: React.ReactNode }) {
return <h1 id={props.id}>{props.children}</h1>;
}
function App() {
return (
<div>
<Title id="main-title">Hello world</Title>
<Counter />
</div>
);
}
// React handles all DOM element creation/updates—you just call `render` once
const root = ReactDOM.createRoot(document.querySelector("#root")!);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);const title = document.createElement("h1");
title.className = "title";
title.textContent = "Hello world!";<h1 class="title">Hello world!</h1>const title = <h1 className="title">Hello world!</h1>;const title = _jsx("h1", { className: "title", children: "Hello world!" });
/*
* Over-simplified for examples sake:
{
type: "h1",
props: {
className: "title",
children: "Hello world!",
},
}
*/const title = <h1>Hello {5 * 5}</h1>;
// <h1>Hello 25</h1>const name = "oli";
const title = <h1>Hello {name}</h1>;
// <h1>Hello oli</h1>const number = Math.random();
const result = <div>{number > 0.5 ? "You won!" : "You lost"}</div>;
// 50% of the time: <div>You won!</div>
// the other 50%: <div>You lost</div>const number = 5 + 4 * 9;
const isEven = number % 2 === 0;
const message = isEven ? "It is even" : "It is odd";const message = if (isEven) { "It is even" } else { "It is odd" };
// this is not valid JS and will cause an errorfunction Title() {
return <h1 className="title">Hello world!</h1>;
}const fruits = ["apple", "orange", "banana"];
function FruitList() {
const items = fruits.map((fruit) => <li key={fruit}>{fruit}</li>);
return <ul>{items}</ul>;
}function Title() {
return <h1 className="title">Hello world!</h1>;
}
function Page() {
return (
<div className="page">
<Title />
</div>
);
}<Title name="oli" />
/**
* The above JSX is transformed into this:
* _jsx(Title, { name: "oli" });
*/function Title(props) {
console.log(props); // { name: "oli" }
return <h1 className="title">Hello world</h1>;
}function Title(props) {
return <h1 className="title">Hello {props.name}</h1>;
}function Page() {
return (
<div className="page">
<Title name="oli" />
<Title name="sam" />
</div>
);
}
/**
* <div class="page">
* <h1 class="title">Hello oli</h1>
* <h1 class="title">Hello sam</h1>
* </div>
*/function Title(props: { name: string }) {
return <h1 className="title">Hello {props.name}</h1>;
}type TitleProps = { name: string };
function Title(props: TitleProps) {
return <h1 className="title">Hello {props.name}</h1>;
}function Page() {
const fullname = "oliver" + " phillips";
return (
<div className="page">
<Title name={fullname} />
<Title name={String(5 * 5)} />
</div>
);
}
/**
* <div class="page">
* <h1 class="title">Hello oliver phillips</h1>
* <h1 class="title">Hello 25</h1>
* </div>
*/<Title>Hello oli</Title>
/**
* The above JSX is transformed into this:
* _jsx(Title, { children: "hello oli" });
*/function Title(props) {
return <h1 className="title">{props.children}</h1>;
}<Title>Hello oli</Title>
// <h1 class="title">Hello oli</h1>// pretend we have defined Image and BigText components above
<Title>
<Image src="hand-wave.svg" />
<BigText>Hello oli</BigText>
</Title>type TitleProps = { children: React.ReactNode };
function Title(props) {
return <h1 className="title">{props.children}</h1>;
}import ReactDOM from "react-dom/client";
function App() {
return (
<Page>
<Title>Hello world!</Title>
<p>Welcome to my page</p>
</Page>
);
}
const div = document.querySelector("#root")!; // The `!` tells TS it's definitely not null
const root = ReactDOM.createRoot(div);
root.render(<App />);function Alerter() {
return <button onClick={() => alert("hello!")}>Say hello</button>;
}function Counter() {
const count = 0;
return <button onClick={() => {}}>{count}</button>;
}import { useState } from "react";
function Counter() {
const stateArray = useState(0);
const count = stateArray[0];
const setCount = stateArray[1];
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}import { useState } from "react";
function Counter(props) {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<FancyButton count={count} setCount={setCount} />
<FancyText>{count}</FancyText>
</div>
);
}
function FancyButton(props) {
function increment() {
props.setCount(props.count + 1);
}
return (
<button className="fancy-button" value={props.count} onClick={increment}>
+ 1
</button>
);
}
function FancyText(props) {
return <p className="fancy-text">{props.children}</p>;
}const [count, setCount] = useState<number>(0);type Status = "loading" | "complete" | "error";
const [status, setStatus] = useState<Status>("loading");type FancyButtonProps = {
count: number;
setCount: React.Dispatch<React.SetStateAction<number>>;
};
function FancyButton(props: FancyButtonProps) {
function increment() {
props.setCount(props.count + 1);
}
return (
<button className="fancy-button" value={props.count} onClick={increment}>
+ 1
</button>
);
}// ...
const [count, setCount] = useState(0);
// ...
setInterval(() => {
setCount((previousCount) => {
const nextCount = previousCount + 1;
return nextCount;
});
}, 1000);
// or more concisely:
// setInterval(() => setCount(c => c + 1), 1000);function ChooseName() {
const [name, setName] = useState("");
function updateName(event) {
event.preventDefault();
setName(event.target.username.value);
}
return (
<form onSubmit={updateName}>
<input name="username" aria-label="Username" />
<button>Update name</button>
<output>Your name is: {username}</output>
</form>
);
}<button onClick={(event) => console.log(event)}>Click</button>function updateName(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
setName(event.target.username.value);
}function ChooseRating() {
const [rating, setRating] = useState(3);
function updateRating(event: React.ChangeEvent<HTMLInputElement>) {
setFruit(+event.target.value);
}
return (
<form>
<input
type="range"
value={rating}
onChange={updateRating}
min="1"
max="5"
aria-label="Rating"
/>
<output>{"⭐️".repeat(rating)}</output>
</form>
);
}function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
});
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);function KeyDisplay(props) {
const [key, setKey] = useState("");
useEffect(() => {
function updateKey(event: KeyboardEvent) {
setKey(event.key);
}
window.addEventListener("keydown", updateKey);
}, []);
return <div>{key}</div>;
}// ...
useEffect(() => {
function updateKey(event: KeyboardEvent) {
setKey(event.key);
}
window.addEventListener("keydown", updateKey);
return () => window.removeEventListener("keydown", updateKey);
}, []);
// ...