|
======================== |
|
CODE SNIPPETS |
|
======================== |
|
TITLE: Install React.dev Project Dependencies |
|
DESCRIPTION: This snippet provides the necessary shell commands to navigate into the project directory and install all required npm dependencies for the react.dev website using Yarn. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/README.md#_snippet_0 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
cd react.dev |
|
``` |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
yarn |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run React.dev Development Server Locally |
|
DESCRIPTION: Instructions to start the local development server for the react.dev website, which is powered by Next.js, and then automatically open the site in your default web browser. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/README.md#_snippet_1 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
yarn dev |
|
``` |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
open http://localhost:3000 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Complete example of React component definition and nesting |
|
DESCRIPTION: A comprehensive example combining the definition of a `MyButton` component and its integration into a `MyApp` component. This illustrates the basic structure of a React application with component creation and composition. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/index.md#_snippet_2 |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
function MyButton() { |
|
return ( |
|
<button> |
|
I'm a button |
|
</button> |
|
); |
|
} |
|
|
|
export default function MyApp() { |
|
return ( |
|
<div> |
|
<h1>Welcome to my app</h1> |
|
<MyButton /> |
|
</div> |
|
); |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Prettier Extension in VS Code |
|
DESCRIPTION: Instructions to install the Prettier extension directly from the VS Code Quick Open palette, enabling automatic code formatting. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/editor-setup.md#_snippet_0 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
ext install esbenp.prettier-vscode |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Example React Compiler Output |
|
DESCRIPTION: This JavaScript code snippet illustrates an example of the output generated by the React Compiler. It shows how the compiler automatically adds memoization logic, such as the `_c` function call and conditional rendering based on a sentinel symbol, to optimize component rendering. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/react-compiler/installation.md#_snippet_7 |
|
|
|
LANGUAGE: JavaScript |
|
CODE: |
|
``` |
|
import { c as _c } from "react/compiler-runtime"; |
|
export default function MyApp() { |
|
const $ = _c(1); |
|
let t0; |
|
if ($[0] === Symbol.for("react.memo_cache_sentinel")) { |
|
t0 = <div>Hello World</div>; |
|
$[0] = t0; |
|
} else { |
|
t0 = $[0]; |
|
} |
|
return t0; |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Stage, Commit, and Push Git Changes |
|
DESCRIPTION: Steps to stage all modified files, commit them with a descriptive message, and then push the changes from your local branch to your forked repository on GitHub. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/README.md#_snippet_4 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
git add -A && git commit -m "My message" |
|
``` |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
git push my-fork-name the-name-of-my-branch |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Complete React Context and Reducer Implementation Example |
|
DESCRIPTION: A comprehensive example demonstrating the complete setup and usage of React Context with `useReducer` for managing a task list. It includes the main application component, context definitions, individual components for adding and listing tasks, and the reducer logic. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/scaling-up-with-reducer-and-context.md#_snippet_16 |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { useReducer } from 'react'; |
|
import AddTask from './AddTask.js'; |
|
import TaskList from './TaskList.js'; |
|
import { TasksContext, TasksDispatchContext } from './TasksContext.js'; |
|
|
|
export default function TaskApp() { |
|
const [tasks, dispatch] = useReducer( |
|
tasksReducer, |
|
initialTasks |
|
); |
|
|
|
return ( |
|
<TasksContext value={tasks}> |
|
<TasksDispatchContext value={dispatch}> |
|
<h1>Day off in Kyoto</h1> |
|
<AddTask /> |
|
<TaskList /> |
|
</TasksDispatchContext> |
|
</TasksContext> |
|
); |
|
} |
|
|
|
function tasksReducer(tasks, action) { |
|
switch (action.type) { |
|
case 'added': { |
|
return [...tasks, { |
|
id: action.id, |
|
text: action.text, |
|
done: false |
|
}]; |
|
} |
|
case 'changed': { |
|
return tasks.map(t => { |
|
if (t.id === action.task.id) { |
|
return action.task; |
|
} else { |
|
return t; |
|
} |
|
}); |
|
} |
|
case 'deleted': { |
|
return tasks.filter(t => t.id !== action.id); |
|
} |
|
default: { |
|
throw Error('Unknown action: ' + action.type); |
|
} |
|
} |
|
} |
|
|
|
const initialTasks = [ |
|
{ id: 0, text: 'Philosopher’s Path', done: true }, |
|
{ id: 1, text: 'Visit the temple', done: false }, |
|
{ id: 2, text: 'Drink matcha', done: false } |
|
]; |
|
``` |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { createContext } from 'react'; |
|
|
|
export const TasksContext = createContext(null); |
|
export const TasksDispatchContext = createContext(null); |
|
``` |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { useState, useContext } from 'react'; |
|
import { TasksDispatchContext } from './TasksContext.js'; |
|
|
|
export default function AddTask() { |
|
const [text, setText] = useState(''); |
|
const dispatch = useContext(TasksDispatchContext); |
|
return ( |
|
<> |
|
<input |
|
placeholder="Add task" |
|
value={text} |
|
onChange={e => setText(e.target.value)} |
|
/> |
|
<button onClick={() => { |
|
setText(''); |
|
dispatch({ |
|
type: 'added', |
|
id: nextId++, |
|
text: text, |
|
}); |
|
}}>Add</button> |
|
</> |
|
); |
|
} |
|
|
|
let nextId = 3; |
|
``` |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { useState, useContext } from 'react'; |
|
import { TasksContext, TasksDispatchContext } from './TasksContext.js'; |
|
|
|
export default function TaskList() { |
|
const tasks = useContext(TasksContext); |
|
return ( |
|
<ul> |
|
{tasks.map(task => ( |
|
<li key={task.id}> |
|
<Task task={task} /> |
|
</li> |
|
))} |
|
</ul> |
|
); |
|
} |
|
|
|
function Task({ task }) { |
|
const [isEditing, setIsEditing] = useState(false); |
|
const dispatch = useContext(TasksDispatchContext); |
|
let taskContent; |
|
if (isEditing) { |
|
taskContent = ( |
|
<> |
|
<input |
|
value={task.text} |
|
onChange={e => { |
|
dispatch({ |
|
type: 'changed', |
|
task: { |
|
...task, |
|
text: e.target.value |
|
} |
|
}); |
|
}} /> |
|
<button onClick={() => setIsEditing(false)}> |
|
Save |
|
</button> |
|
</> |
|
); |
|
} else { |
|
taskContent = ( |
|
<> |
|
{task.text} |
|
<button onClick={() => setIsEditing(true)}> |
|
Edit |
|
</button> |
|
</> |
|
); |
|
} |
|
return ( |
|
<label> |
|
<input |
|
type="checkbox" |
|
checked={task.done} |
|
onChange={e => { |
|
dispatch({ |
|
type: 'changed', |
|
task: { |
|
...task, |
|
done: e.target.checked |
|
} |
|
}); |
|
}} |
|
/> |
|
{taskContent} |
|
<button onClick={() => { |
|
dispatch({ |
|
type: 'deleted', |
|
id: task.id |
|
}); |
|
}}> |
|
Delete |
|
</button> |
|
</label> |
|
); |
|
} |
|
``` |
|
|
|
LANGUAGE: css |
|
CODE: |
|
``` |
|
button { margin: 5px; } |
|
li { list-style-type: none; } |
|
ul, li { margin: 0; padding: 0; } |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Create a New Git Branch for Contributions |
|
DESCRIPTION: Commands to ensure your local Git repository is synchronized with the latest changes from the main branch and then create a new feature branch for making your contributions. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/README.md#_snippet_2 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
git checkout main |
|
``` |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
git pull origin main |
|
``` |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
git checkout -b the-name-of-my-branch |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Basic React Functional Component Example |
|
DESCRIPTION: This JavaScript snippet demonstrates a simple React functional component named `Greeting` that accepts a `name` prop and renders an `h1` tag. The `App` component then uses this `Greeting` component to display 'Hello, world', illustrating basic component composition and rendering in React. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/installation.md#_snippet_0 |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
function Greeting({ name }) { |
|
return <h1>Hello, {name}</h1>; |
|
} |
|
|
|
export default function App() { |
|
return <Greeting name="world" /> |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Full React application example with createElement |
|
DESCRIPTION: Provides a complete, runnable React application demonstrating the use of `createElement` for both HTML elements and custom components. This example includes the necessary imports and a CSS stylesheet to illustrate a fully functional setup without JSX. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/createElement.md#_snippet_7 |
|
|
|
LANGUAGE: JavaScript |
|
CODE: |
|
``` |
|
import { createElement } from 'react'; |
|
|
|
function Greeting({ name }) { |
|
return createElement( |
|
'h1', |
|
{ className: 'greeting' }, |
|
'Hello ', |
|
createElement('i', null, name), |
|
'. Welcome!' |
|
); |
|
} |
|
|
|
export default function App() { |
|
return createElement( |
|
Greeting, |
|
{ name: 'Taylor' } |
|
); |
|
} |
|
``` |
|
|
|
LANGUAGE: CSS |
|
CODE: |
|
``` |
|
.greeting { |
|
color: darkgreen; |
|
font-family: Georgia; |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Full React Application Structure Example |
|
DESCRIPTION: This comprehensive example illustrates the typical file structure and content for a complete React application. It includes the `public/index.html` file defining the root DOM element, `src/index.js` for the main rendering logic, and `src/App.js` showcasing a functional React component with state management. This setup provides a runnable boilerplate for a client-side React app. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-dom/client/createRoot.md#_snippet_7 |
|
|
|
LANGUAGE: html |
|
CODE: |
|
``` |
|
<!DOCTYPE html> |
|
<html> |
|
<head><title>My app</title></head> |
|
<body> |
|
<!-- This is the DOM node --> |
|
<div id="root"></div> |
|
</body> |
|
</html> |
|
``` |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { createRoot } from 'react-dom/client'; |
|
import App from './App.js'; |
|
import './styles.css'; |
|
|
|
const root = createRoot(document.getElementById('root')); |
|
root.render(<App />); |
|
``` |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { useState } from 'react'; |
|
|
|
export default function App() { |
|
return ( |
|
<> |
|
<h1>Hello, world!</h1> |
|
<Counter /> |
|
</> |
|
); |
|
} |
|
|
|
function Counter() { |
|
const [count, setCount] = useState(0); |
|
return ( |
|
<button onClick={() => setCount(count + 1)}> |
|
You clicked me {count} times |
|
</button> |
|
); |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Comprehensive React App Pre-rendering with Activity and ViewTransition |
|
DESCRIPTION: A full React application example showcasing advanced pre-rendering strategies using `unstable_Activity` and `unstable_ViewTransition`. This setup pre-renders video details and other components, ensuring data is fetched and UI is prepared before navigation. It includes `App.js` for routing and activity management, `Details.js` for handling video specifics with suspense, and `Home.js` for the main video list and search functionality. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/blog/2025/04/23/react-labs-view-transitions-activity-and-more.md#_snippet_237 |
|
|
|
LANGUAGE: jsx |
|
CODE: |
|
``` |
|
import { unstable_ViewTransition as ViewTransition, unstable_Activity as Activity, use } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; import {fetchVideos} from './data' |
|
|
|
export default function App() { |
|
const { url } = useRouter(); |
|
const videoId = url.split("/").pop(); |
|
const videos = use(fetchVideos()); |
|
|
|
return ( |
|
<ViewTransition> |
|
{/* Render videos in Activity to pre-render them */} |
|
{videos.map(({id}) => ( |
|
<Activity key={id} mode={videoId === id ? 'visible' : 'hidden'}> |
|
<Details id={id}/> |
|
</Activity> |
|
))} |
|
<Activity mode={url === '/' ? 'visible' : 'hidden'}> |
|
<Home /> |
|
</Activity> |
|
</ViewTransition> |
|
); |
|
} |
|
``` |
|
|
|
LANGUAGE: jsx |
|
CODE: |
|
``` |
|
import { use, Suspense, unstable_ViewTransition as ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons"; |
|
|
|
function VideoDetails({id}) { |
|
// Animate from Suspense fallback to content. |
|
// If this is pre-rendered then the fallback |
|
// won't need to show. |
|
return ( |
|
<Suspense |
|
fallback={ |
|
// Animate the fallback down. |
|
<ViewTransition exit="slide-down"> |
|
<VideoInfoFallback /> |
|
</ViewTransition> |
|
} |
|
> |
|
{/* Animate the content up */} |
|
<ViewTransition enter="slide-up"> |
|
<VideoInfo id={id} /> |
|
</ViewTransition> |
|
</Suspense> |
|
); |
|
} |
|
|
|
function VideoInfoFallback() { |
|
return ( |
|
<> |
|
<div className="fallback title"></div> |
|
<div className="fallback description"></div> |
|
</> |
|
); |
|
} |
|
|
|
export default function Details({id}) { |
|
const { url, navigateBack } = useRouter(); |
|
const video = use(fetchVideo(id)); |
|
|
|
return ( |
|
<Layout |
|
heading={ |
|
<div |
|
className="fit back" |
|
onClick={() => { |
|
navigateBack("/"); |
|
}} |
|
> |
|
<ChevronLeft /> Back |
|
</div> |
|
} |
|
> |
|
<div className="details"> |
|
<Thumbnail video={video} large> |
|
<VideoControls /> |
|
</Thumbnail> |
|
<VideoDetails id={video.id} /> |
|
</div> |
|
</Layout> |
|
); |
|
} |
|
|
|
function VideoInfo({ id }) { |
|
const details = use(fetchVideoDetails(id)); |
|
return ( |
|
<> |
|
<p className="info-title">{details.title}</p> |
|
<p className="info-description">{details.description}</p> |
|
</> |
|
); |
|
} |
|
``` |
|
|
|
LANGUAGE: jsx |
|
CODE: |
|
``` |
|
import { useId, useState, use, useDeferredValue, unstable_ViewTransition as ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons"; |
|
|
|
function SearchList({searchText, videos}) { |
|
// Activate with useDeferredValue ("when") |
|
const deferredSearchText = useDeferredValue(searchText); |
|
const filteredVideos = filterVideos(videos, deferredSearchText); |
|
return ( |
|
<div className="video-list"> |
|
{filteredVideos.length === 0 && ( |
|
<div className="no-results">No results</div> |
|
)} |
|
<div className="videos"> |
|
{filteredVideos.map((video) => ( |
|
// Animate each item in list ("what") |
|
<ViewTransition key={video.id}> |
|
<Video video={video} /> |
|
</ViewTransition> |
|
))} |
|
</div> |
|
</div> |
|
); |
|
} |
|
|
|
export default function Home() { |
|
const videos = use(fetchVideos()); |
|
const count = videos.length; |
|
const [searchText, setSearchText] = useState(''); |
|
|
|
return ( |
|
<Layout heading={<div className="fit">{count} Videos</div>}> |
|
<SearchInput value={searchText} onChange={setSearchText} /> |
|
<SearchList videos={videos} searchText={searchText} /> |
|
</Layout> |
|
); |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install React 19 with npm |
|
DESCRIPTION: Command to install React and React DOM version 19.0.0 using npm, ensuring an exact version match for stability during the upgrade process. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/blog/2024/04/25/react-19-upgrade-guide.md#_snippet_0 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npm install --save-exact react@^19.0.0 react-dom@^19.0.0 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Complete React Suspense Data Fetching Example |
|
DESCRIPTION: A comprehensive example showcasing how React Suspense can be used for data fetching. This multi-file setup includes an `App` component for initial rendering, an `ArtistPage` with nested `Suspense`, an `Albums` component that uses the `use()` hook for data, and a mock `data.js` utility simulating asynchronous data retrieval. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md#_snippet_3 |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import { useState } from 'react'; |
|
import ArtistPage from './ArtistPage.js'; |
|
|
|
export default function App() { |
|
const [show, setShow] = useState(false); |
|
if (show) { |
|
return ( |
|
<ArtistPage |
|
artist={{ |
|
id: 'the-beatles', |
|
name: 'The Beatles', |
|
}} |
|
/> |
|
); |
|
} else { |
|
return ( |
|
<button onClick={() => setShow(true)}> |
|
Open The Beatles artist page |
|
</button> |
|
); |
|
} |
|
} |
|
``` |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import { Suspense } from 'react'; |
|
import Albums from './Albums.js'; |
|
|
|
export default function ArtistPage({ artist }) { |
|
return ( |
|
<> |
|
<h1>{artist.name}</h1> |
|
<Suspense fallback={<Loading />}> |
|
<Albums artistId={artist.id} /> |
|
</Suspense> |
|
</> |
|
); |
|
} |
|
|
|
function Loading() { |
|
return <h2>🌀 Loading...</h2>; |
|
} |
|
``` |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
import {use} from 'react'; |
|
import { fetchData } from './data.js'; |
|
|
|
export default function Albums({ artistId }) { |
|
const albums = use(fetchData(`/${artistId}/albums`)); |
|
return ( |
|
<ul> |
|
{albums.map(album => ( |
|
<li key={album.id}> |
|
{album.title} ({album.year}) |
|
</li> |
|
))} |
|
</ul> |
|
); |
|
} |
|
``` |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
// Note: the way you would do data fetching depends on |
|
// the framework that you use together with Suspense. |
|
// Normally, the caching logic would be inside a framework. |
|
|
|
let cache = new Map(); |
|
|
|
export function fetchData(url) { |
|
if (!cache.has(url)) { |
|
cache.set(url, getData(url)); |
|
} |
|
return cache.get(url); |
|
} |
|
|
|
async function getData(url) { |
|
if (url === '/the-beatles/albums') { |
|
return await getAlbums(); |
|
} else { |
|
throw Error('Not implemented'); |
|
} |
|
} |
|
|
|
async function getAlbums() { |
|
// Add a fake delay to make waiting noticeable. |
|
await new Promise(resolve => { |
|
setTimeout(resolve, 3000); |
|
}); |
|
|
|
return [{ |
|
id: 13, |
|
title: 'Let It Be', |
|
year: 1970 |
|
}, { |
|
id: 12, |
|
title: 'Abbey Road', |
|
year: 1969 |
|
}, { |
|
id: 11, |
|
title: 'Yellow Submarine', |
|
year: 1969 |
|
}, { |
|
id: 10, |
|
title: 'The Beatles', |
|
year: 1968 |
|
}, { |
|
id: 9, |
|
title: 'Magical Mystery Tour', |
|
year: 1967 |
|
}, { |
|
id: 8, |
|
title: 'Sgt. Pepper\'s Lonely Hearts Club Band', |
|
year: 1967 |
|
}, { |
|
id: 7, |
|
title: 'Revolver', |
|
year: 1966 |
|
}, { |
|
id: 6, |
|
title: 'Rubber Soul', |
|
year: 1965 |
|
}, { |
|
id: 5, |
|
title: 'Help!', |
|
year: 1965 |
|
}, { |
|
id: 4, |
|
title: 'Beatles For Sale', |
|
year: 1964 |
|
}, { |
|
id: 3, |
|
title: 'A Hard Day\'s Night', |
|
year: 1964 |
|
}, { |
|
id: 2, |
|
title: 'With The Beatles', |
|
year: 1963 |
|
}, { |
|
id: 1, |
|
title: 'Please Please Me', |
|
year: 1963 |
|
}]; |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install React 19 with Yarn |
|
DESCRIPTION: Command to install React and React DOM version 19.0.0 using Yarn, ensuring an exact version match for stability during the upgrade process. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/blog/2024/04/25/react-19-upgrade-guide.md#_snippet_1 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
yarn add --exact react@^19.0.0 react-dom@^19.0.0 |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Complete React Component Prop Passing Example |
|
DESCRIPTION: This comprehensive example includes the final `Square` and `Board` components, demonstrating the complete setup for passing and utilizing props in a React application. It also includes the associated CSS for styling the components. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/tutorial-tic-tac-toe.md#_snippet_13 |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
function Square({ value }) { |
|
return <button className="square">{value}</button>; |
|
} |
|
|
|
export default function Board() { |
|
return ( |
|
<> |
|
<div className="board-row"> |
|
<Square value="1" /> |
|
<Square value="2" /> |
|
<Square value="3" /> |
|
</div> |
|
<div className="board-row"> |
|
<Square value="4" /> |
|
<Square value="5" /> |
|
<Square value="6" /> |
|
</div> |
|
<div className="board-row"> |
|
<Square value="7" /> |
|
<Square value="8" /> |
|
<Square value="9" /> |
|
</div> |
|
</> |
|
); |
|
} |
|
``` |
|
|
|
LANGUAGE: css |
|
CODE: |
|
``` |
|
* { |
|
box-sizing: border-box; |
|
} |
|
|
|
body { |
|
font-family: sans-serif; |
|
margin: 20px; |
|
padding: 0; |
|
} |
|
|
|
.square { |
|
background: #fff; |
|
border: 1px solid #999; |
|
float: left; |
|
font-size: 24px; |
|
font-weight: bold; |
|
line-height: 34px; |
|
height: 34px; |
|
margin-right: -1px; |
|
margin-top: -1px; |
|
padding: 0; |
|
text-align: center; |
|
width: 34px; |
|
} |
|
|
|
.board-row:after { |
|
clear: both; |
|
content: ''; |
|
display: table; |
|
} |
|
|
|
.status { |
|
margin-bottom: 10px; |
|
} |
|
.game { |
|
display: flex; |
|
flex-direction: row; |
|
} |
|
|
|
.game-info { |
|
margin-left: 20px; |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Complete React Function Component Migration Example |
|
DESCRIPTION: This is the complete example of the `Greeting` component after being fully migrated from a class component to a functional component. It showcases the simplified syntax for defining components and accessing props, along with its usage within the `App` component, demonstrating a fully converted functional component setup. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Component.md#_snippet_42 |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
function Greeting({ name }) { |
|
return <h1>Hello, {name}!</h1>; |
|
} |
|
|
|
export default function App() { |
|
return ( |
|
<> |
|
<Greeting name="Sara" /> |
|
<Greeting name="Cahal" /> |
|
<Greeting name="Edite" /> |
|
</> |
|
); |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Run Project Code Quality Checks |
|
DESCRIPTION: This command executes a suite of pre-commit checks, including Prettier for code formatting, ESLint for linting, and type validation, to ensure code quality and consistency across the project. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/README.md#_snippet_3 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
yarn check-all |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: React Hook: useEffect(setup, dependencies?) |
|
DESCRIPTION: Detailed reference for the `useEffect` React Hook, explaining its signature, parameters (`setup` function and optional `dependencies` array), return value, and critical caveats for proper usage in React components. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/useEffect.md#_snippet_0 |
|
|
|
LANGUAGE: APIDOC |
|
CODE: |
|
``` |
|
useEffect(setup, dependencies?) |
|
Description: A React Hook that lets you synchronize a component with an external system. Call at the top level of your component to declare an Effect. |
|
|
|
Parameters: |
|
setup: |
|
Type: function |
|
Description: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. When your component is added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. After your component is removed from the DOM, React will run your cleanup function. |
|
dependencies (optional): |
|
Type: Array<any> |
|
Description: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is configured for React, it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the `Object.is` comparison. If you omit this argument, your Effect will re-run after every re-render of the component. |
|
|
|
Returns: undefined |
|
|
|
Caveats: |
|
- `useEffect` is a Hook, so you can only call it at the top level of your component or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it. |
|
- If you're not trying to synchronize with some external system, you probably don't need an Effect. |
|
- When Strict Mode is on, React will run one extra development-only setup+cleanup cycle before the first real setup. This is a stress-test that ensures that your cleanup logic "mirrors" your setup logic and that it stops or undoes whatever the setup is doing. If this causes a problem, implement the cleanup function. |
|
- If some of your dependencies are objects or functions defined inside the component, there is a risk that they will cause the Effect to re-run more often than needed. To fix this, remove unnecessary object and function dependencies. You can also extract state updates and non-reactive logic outside of your Effect. |
|
- If your Effect wasn't caused by an interaction (like a click), React will generally let the browser paint the updated screen first before running your Effect. If your Effect is doing something visual (for example, positioning a tooltip), and the delay is noticeable (for example, it flickers), replace `useEffect` with `useLayoutEffect`. |
|
- If your Effect is caused by an interaction (like a click), React may run your Effect before the browser paints the updated screen. This ensures that the result of the Effect can be observed by the event system. Usually, this works as expected. However, if you must defer the work until after paint, such as an `alert()`, you can use `setTimeout`. |
|
- Even if your Effect was caused by an interaction (like a click), React may allow the browser to repaint the screen before processing the state updates inside your Effect. Usually, this works as expected. However, if you must block the browser from repainting the screen, you need to replace `useEffect` with `useLayoutEffect`. |
|
- Effects only run on the client. They don't run during server rendering. |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: React App Entry Point for Context Example |
|
DESCRIPTION: The main `App` component imports `List` and `Row` components along with product data. It renders the `List` component, demonstrating the overall application structure for the context example. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/cloneElement.md#_snippet_20 |
|
|
|
LANGUAGE: JavaScript |
|
CODE: |
|
``` |
|
import List from './List.js'; |
|
import Row from './Row.js'; |
|
import { products } from './data.js'; |
|
|
|
export default function App() { |
|
return ( |
|
<List |
|
items={products} |
|
renderItem={(product) => |
|
<Row title={product.title} /> |
|
} |
|
/> |
|
); |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Migrate `ReactDOM.render` to `ReactDOM.createRoot` in React 19 |
|
DESCRIPTION: React 19 removes `ReactDOM.render`. This example shows how to update your application's entry point to use `ReactDOM.createRoot` for initial rendering, which is the recommended approach for concurrent mode. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/blog/2024/04/25/react-19-upgrade-guide.md#_snippet_16 |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
// Before |
|
import {render} from 'react-dom'; |
|
render(<App />, document.getElementById('root')); |
|
|
|
// After |
|
import {createRoot} from 'react-dom/client'; |
|
const root = createRoot(document.getElementById('root')); |
|
root.render(<App />); |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Configure React Compiler for React Router with Vite |
|
DESCRIPTION: Sets up React Compiler within a React Router project that uses Vite. This involves installing `vite-plugin-babel` and configuring it in `vite.config.js` to apply `babel-plugin-react-compiler` to relevant files, ensuring compatibility with React Router's development setup. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/react-compiler/installation.md#_snippet_4 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npm install vite-plugin-babel |
|
``` |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
// vite.config.js |
|
import { defineConfig } from "vite"; |
|
import babel from "vite-plugin-babel"; |
|
import { reactRouter } from "@react-router/dev/vite"; |
|
|
|
const ReactCompilerConfig = { /* ... */ }; |
|
|
|
export default defineConfig({ |
|
plugins: [ |
|
reactRouter(), |
|
babel({ |
|
filter: /\.[jt]sx?$/, |
|
babelConfig: { |
|
presets: ["@babel/preset-typescript"], // if you use TypeScript |
|
plugins: [ |
|
["babel-plugin-react-compiler", ReactCompilerConfig] |
|
] |
|
} |
|
}) |
|
] |
|
}); |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Complete example of lifting state up in React |
|
DESCRIPTION: This comprehensive example combines all steps of lifting state up: `MyApp` manages the shared `count` state and `handleClick` function, passing them as props to `MyButton`. `MyButton` then consumes these props to display the shared count and trigger the parent's handler, demonstrating how multiple components can share and update the same state. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/index.md#_snippet_24 |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { useState } from 'react'; |
|
|
|
export default function MyApp() { |
|
const [count, setCount] = useState(0); |
|
|
|
function handleClick() { |
|
setCount(count + 1); |
|
} |
|
|
|
return ( |
|
<div> |
|
<h1>Counters that update together</h1> |
|
<MyButton count={count} onClick={handleClick} /> |
|
<MyButton count={count} onClick={handleClick} /> |
|
</div> |
|
); |
|
} |
|
|
|
function MyButton({ count, onClick }) { |
|
return ( |
|
<button onClick={onClick}> |
|
Clicked {count} times |
|
</button> |
|
); |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Comprehensive example of data display and inline styling in React |
|
DESCRIPTION: A complete example showcasing how to display dynamic data (user name, image URL, image size) within JSX. It includes string concatenation in attributes (`alt`) and inline styling using JavaScript objects (`style={{ width: ..., height: ... }}`). |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/index.md#_snippet_8 |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
const user = { |
|
name: 'Hedy Lamarr', |
|
imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg', |
|
imageSize: 90, |
|
}; |
|
|
|
export default function Profile() { |
|
return ( |
|
<> |
|
<h1>{user.name}</h1> |
|
<img |
|
className="avatar" |
|
src={user.imageUrl} |
|
alt={'Photo of ' + user.name} |
|
style={{ |
|
width: user.imageSize, |
|
height: user.imageSize |
|
}} |
|
/> |
|
</> |
|
); |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Complete React Context Example with Heading and Section Components |
|
DESCRIPTION: This comprehensive example demonstrates the full implementation of React Context for managing heading levels. It includes the main `Page` component, `Section` (which will eventually provide context), `Heading` (which consumes context), and the `LevelContext` definition, along with basic styling. This setup illustrates how context simplifies prop management across a component hierarchy. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/passing-data-deeply-with-context.md#_snippet_10 |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import Heading from './Heading.js'; |
|
import Section from './Section.js'; |
|
|
|
export default function Page() { |
|
return ( |
|
<Section level={1}> |
|
<Heading>Title</Heading> |
|
<Section level={2}> |
|
<Heading>Heading</Heading> |
|
<Heading>Heading</Heading> |
|
<Heading>Heading</Heading> |
|
<Section level={3}> |
|
<Heading>Sub-heading</Heading> |
|
<Heading>Sub-heading</Heading> |
|
<Heading>Sub-heading</Heading> |
|
<Section level={4}> |
|
<Heading>Sub-sub-heading</Heading> |
|
<Heading>Sub-sub-heading</Heading> |
|
<Heading>Sub-sub-heading</Heading> |
|
</Section> |
|
</Section> |
|
</Section> |
|
</Section> |
|
); |
|
} |
|
``` |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
export default function Section({ children }) { |
|
return ( |
|
<section className="section"> |
|
{children} |
|
</section> |
|
); |
|
} |
|
``` |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { useContext } from 'react'; |
|
import { LevelContext } from './LevelContext.js'; |
|
|
|
export default function Heading({ children }) { |
|
const level = useContext(LevelContext); |
|
switch (level) { |
|
case 1: |
|
return <h1>{children}</h1>; |
|
case 2: |
|
return <h2>{children}</h2>; |
|
case 3: |
|
return <h3>{children}</h3>; |
|
case 4: |
|
return <h4>{children}</h4>; |
|
case 5: |
|
return <h5>{children}</h5>; |
|
case 6: |
|
return <h6>{children}</h6>; |
|
default: |
|
throw Error('Unknown level: ' + level); |
|
} |
|
} |
|
``` |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { createContext } from 'react'; |
|
|
|
export const LevelContext = createContext(1); |
|
``` |
|
|
|
LANGUAGE: css |
|
CODE: |
|
``` |
|
.section { |
|
padding: 10px; |
|
margin: 5px; |
|
border-radius: 5px; |
|
border: 1px solid #aaa; |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install React and ReactDOM via npm |
|
DESCRIPTION: Installs the core React library and ReactDOM for web rendering using npm. This command should be executed in your project's root directory to add necessary dependencies. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/add-react-to-an-existing-project.md#_snippet_0 |
|
|
|
LANGUAGE: Shell |
|
CODE: |
|
``` |
|
npm install react react-dom |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Package Dependencies for React ViewTransition Example |
|
DESCRIPTION: This `package.json` file lists the necessary dependencies for running the React ViewTransition example. It specifies `experimental` versions for `react` and `react-dom` to ensure compatibility with the `unstable_ViewTransition` API, along with `react-scripts` for development utilities. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/ViewTransition.md#_snippet_15 |
|
|
|
LANGUAGE: json |
|
CODE: |
|
``` |
|
{ |
|
"dependencies": { |
|
"react": "experimental", |
|
"react-dom": "experimental", |
|
"react-scripts": "latest" |
|
} |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install React Compiler Babel Plugin |
|
DESCRIPTION: Installs the `babel-plugin-react-compiler` as a development dependency using npm, Yarn, or pnpm. The `@rc` tag ensures the installation of the latest release candidate version, which is recommended for current usage. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/react-compiler/installation.md#_snippet_0 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npm install -D babel-plugin-react-compiler@rc |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
yarn add -D babel-plugin-react-compiler@rc |
|
``` |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
pnpm install -D babel-plugin-react-compiler@rc |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install Vite for a new React project |
|
DESCRIPTION: This command initializes a new React project using Vite, creating a directory named 'my-app' and setting up the basic React template. Vite provides a fast and lean development experience. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/learn/build-a-react-app-from-scratch.md#_snippet_0 |
|
|
|
LANGUAGE: bash |
|
CODE: |
|
``` |
|
npm create vite@latest my-app -- --template react |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: React Component Animation with useEffect and useRef |
|
DESCRIPTION: This example demonstrates how to integrate a third-party animation library (`FadeInAnimation`) with a React component. It uses `useRef` to get a reference to the DOM node and `useEffect` to manage the animation's lifecycle, starting it when the component mounts and stopping it on unmount. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/useEffect.md#_snippet_5 |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
import { useState, useEffect, useRef } from 'react'; |
|
import { FadeInAnimation } from './animation.js'; |
|
|
|
function Welcome() { |
|
const ref = useRef(null); |
|
|
|
useEffect(() => { |
|
const animation = new FadeInAnimation(ref.current); |
|
animation.start(1000); |
|
return () => { |
|
animation.stop(); |
|
}; |
|
}, []); |
|
|
|
return ( |
|
<h1 |
|
ref={ref} |
|
style={{ |
|
opacity: 0, |
|
color: 'white', |
|
padding: 50, |
|
textAlign: 'center', |
|
fontSize: 50, |
|
backgroundImage: 'radial-gradient(circle, rgba(63,94,251,1) 0%, rgba(252,70,107,1) 100%)' |
|
}} |
|
> |
|
Welcome |
|
</h1> |
|
); |
|
} |
|
|
|
export default function App() { |
|
const [show, setShow] = useState(false); |
|
return ( |
|
<> |
|
<button onClick={() => setShow(!show)}> |
|
{show ? 'Remove' : 'Show'} |
|
</button> |
|
<hr /> |
|
{show && <Welcome />} |
|
</> |
|
); |
|
} |
|
``` |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
export class FadeInAnimation { |
|
constructor(node) { |
|
this.node = node; |
|
} |
|
start(duration) { |
|
this.duration = duration; |
|
if (this.duration === 0) { |
|
// Jump to end immediately |
|
this.onProgress(1); |
|
} else { |
|
this.onProgress(0); |
|
// Start animating |
|
this.startTime = performance.now(); |
|
this.frameId = requestAnimationFrame(() => this.onFrame()); |
|
} |
|
} |
|
onFrame() { |
|
const timePassed = performance.now() - this.startTime; |
|
const progress = Math.min(timePassed / this.duration, 1); |
|
this.onProgress(progress); |
|
if (progress < 1) { |
|
// We still have more frames to paint |
|
this.frameId = requestAnimationFrame(() => this.onFrame()); |
|
} |
|
} |
|
onProgress(progress) { |
|
this.node.style.opacity = progress; |
|
} |
|
stop() { |
|
cancelAnimationFrame(this.frameId); |
|
this.startTime = null; |
|
this.frameId = null; |
|
this.duration = 0; |
|
} |
|
} |
|
``` |
|
|
|
LANGUAGE: css |
|
CODE: |
|
``` |
|
label, button { display: block; margin-bottom: 20px; } |
|
html, body { min-height: 300px; } |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: React Packing List Component (Initial Setup) |
|
DESCRIPTION: This React component defines an `Item` and `PackingList` to display a list of items. It serves as the starting point for demonstrating conditional rendering, showing items with `name` and `importance` props without special handling for importance. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/blog/2023/03/16/introducing-react-dev.md#_snippet_3 |
|
|
|
LANGUAGE: javascript |
|
CODE: |
|
``` |
|
function Item({ name, importance }) { |
|
return ( |
|
<li className="item"> |
|
{name} |
|
</li> |
|
); |
|
} |
|
|
|
export default function PackingList() { |
|
return ( |
|
<section> |
|
<h1>Sally Ride's Packing List</h1> |
|
<ul> |
|
<Item |
|
importance={9} |
|
name="Space suit" |
|
/> |
|
<Item |
|
importance={0} |
|
name="Helmet with a golden leaf" |
|
/> |
|
<Item |
|
importance={6} |
|
name="Photo of Tam" |
|
/> |
|
</ul> |
|
</section> |
|
); |
|
} |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Correctly Pass Options to React createRoot |
|
DESCRIPTION: Highlights a common mistake of passing options to `root.render()` instead of `createRoot()`. It provides both incorrect and correct code examples to guide developers on the proper way to configure root options. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-dom/client/createRoot.md#_snippet_17 |
|
|
|
LANGUAGE: js |
|
CODE: |
|
``` |
|
// 🚩 Wrong: root.render only takes one argument. |
|
root.render(App, {onUncaughtError}); |
|
|
|
// ✅ Correct: pass options to createRoot. |
|
const root = createRoot(container, {onUncaughtError}); |
|
root.render(<App />); |
|
``` |
|
|
|
---------------------------------------- |
|
|
|
TITLE: Install ESLint React Hooks Plugin RC |
|
DESCRIPTION: Commands to install `[email protected]`, which now integrates the functionality previously found in `eslint-plugin-react-compiler`. This update simplifies ESLint setup for React projects. |
|
|
|
SOURCE: https://github.com/reactjs/react.dev/blob/main/src/content/blog/2025/04/21/react-compiler-rc.md#_snippet_1 |
|
|
|
LANGUAGE: npm |
|
CODE: |
|
``` |
|
npm install --save-dev [email protected] |
|
``` |
|
|
|
LANGUAGE: pnpm |
|
CODE: |
|
``` |
|
pnpm add --save-dev [email protected] |
|
``` |
|
|
|
LANGUAGE: yarn |
|
CODE: |
|
``` |
|
yarn add --dev [email protected] |
|
``` |