File size: 40,418 Bytes
25f22bf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 |
======================== 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] ``` |