From 1ae25980bd37013f947da88c6fecbcf25758cd5a Mon Sep 17 00:00:00 2001 From: Jakub Drozdek Date: Fri, 3 Dec 2021 01:01:19 +0100 Subject: [PATCH 1/2] Translate Your first component --- beta/src/pages/learn/describing-the-ui.md | 4 +- .../importing-and-exporting-components.md | 814 ++++++++--------- beta/src/pages/learn/your-first-component.md | 852 +++++++++--------- beta/src/sidebarLearn.json | 4 +- 4 files changed, 826 insertions(+), 848 deletions(-) diff --git a/beta/src/pages/learn/describing-the-ui.md b/beta/src/pages/learn/describing-the-ui.md index 2ee7b9563..6e5ab65be 100644 --- a/beta/src/pages/learn/describing-the-ui.md +++ b/beta/src/pages/learn/describing-the-ui.md @@ -55,7 +55,7 @@ img { -Read **[Your First Component](/learn/your-first-component)** to learn how to declare and use React components. +Read **[Twój pierwszy komponent](/learn/your-first-component)** to learn how to declare and use React components. @@ -521,6 +521,6 @@ Read **[Keeping Components Pure](/learn/keeping-components-pure)** to learn how ## What's next? {/_whats-next_/} -Head over to [Your First Component](/learn/your-first-component) to start reading this chapter page by page! +Head over to [Twój pierwszy komponent](/learn/your-first-component) to start reading this chapter page by page! Or, if you're already familiar with these topics, why not read about [Adding Interactivity](/learn/adding-interactivity)? diff --git a/beta/src/pages/learn/importing-and-exporting-components.md b/beta/src/pages/learn/importing-and-exporting-components.md index 1583eab6e..8f5a7ebd8 100644 --- a/beta/src/pages/learn/importing-and-exporting-components.md +++ b/beta/src/pages/learn/importing-and-exporting-components.md @@ -1,416 +1,398 @@ ---- -title: Importing and Exporting Components ---- - - - -The magic of components lies in their reusability: you can create components that are composed of other components. But as you nest more and more components, it often makes sense to start splitting them into different files. This lets you keep your files easy to scan and reuse components in more places. - - - - - -* What a root component file is -* How to import and export a component -* When to use default and named imports and exports -* How to import and export multiple components from one file -* How to split components into multiple files - - - -## The root component file {/*the-root-component-file*/} - -In [Your First Component](/learn/your-first-component), you made a `Profile` component and a `Gallery` component that renders it: - - - -```js -function Profile() { - return ( - Katherine Johnson - ); -} - -export default function Gallery() { - return ( -
-

Amazing scientists

- - - -
- ); -} -``` - -```css -img { margin: 0 10px 10px 0; height: 90px; } -``` - -
- -These currently live in a **root component file,** named `App.js` in this example. In [Create React App](https://create-react-app.dev/), your app lives in `src/App.js`. Depending on your setup, your root component could be in another file, though. If you use a framework with file-based routing, such as Next.js, your root component will be different for every page. - -## Exporting and importing a component {/*exporting-and-importing-a-component*/} - -What if you want to change the landing screen in the future and put a list of science books there? Or place all the profiles somewhere else? It makes sense to move `Gallery` and `Profile` out of the root component file. This will make them more modular and reusable in other files. You can move a component in three steps: - -1. **Make** a new JS file to put the components in. -2. **Export** your function component from that file (using either [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_the_default_export) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_named_exports) exports). -3. **Import** it in the file where you’ll use the component (using the corresponding technique for importing [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#importing_defaults) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#import_a_single_export_from_a_module) exports). - -Here both `Profile` and `Gallery` have been moved out of `App.js` into a new file called `Gallery.js`. Now you can change `App.js` to import `Gallery` from `Gallery.js`: - - - -```js App.js -import Gallery from './Gallery.js'; - -export default function App() { - return ( - - ); -} -``` - -```js Gallery.js -function Profile() { - return ( - Alan L. Hart - ); -} - -export default function Gallery() { - return ( -
-

Amazing scientists

- - - -
- ); -} -``` - -```css -img { margin: 0 10px 10px 0; height: 90px; } -``` - -
- -Notice how this example is broken down into two component files now: - -1. `Gallery.js`: - - Defines the `Profile` component which is only used within the same file and is not exported. - - Exports the `Gallery` component as a **default export**. -2. `App.js`: - - Imports `Gallery` as a **default import** from `Gallery.js`. - - Exports the root `App` component as a **default export**. - - - - -You may encounter files that leave off the `.js` file extension like so: - -```js -import Gallery from './Gallery'; -``` - -Either `'./Gallery.js'` or `'./Gallery'` will work with React, though the former is closer to how [native ES Modules](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Modules) work. - - - - - -There are two primary ways to export values with JavaScript: default exports and named exports. So far, our examples have only used default exports. But you can use one or both of them in the same file. **A file can have no more than one _default_ export, but it can have as many _named_ exports as you like.** - -![Default and named exports](/images/docs/illustrations/i_import-export.svg) - -How you export your component dictates how you must import it. You will get an error if you try to import a default export the same way you would a named export! This chart can help you keep track: - -| Syntax | Export statement | Import statement | -| ----------- | ----------- | ----------- | -| Default | `export default function Button() {}` | `import Button from './button.js';` | -| Named | `export function Button() {}` | `import { Button } from './button.js';` | - -When you write a _default_ import, you can put any name you want after `import`. For example, you could write `import Banana from './button.js'` instead and it would still provide you with the same default export. In contrast, with named imports, the name has to match on both sides. That's why they are called _named_ imports! - -**People often use default exports if the file exports only one component, and use named exports if it exports multiple components and values.** Regardless of which coding style you prefer, always give meaningful names to your component functions and the files that contain them. Components without names, like `export default () => {}`, are discouraged because they make debugging harder. - - - -## Exporting and importing multiple components from the same file {/*exporting-and-importing-multiple-components-from-the-same-file*/} - -What if you want to show just one `Profile` instead of a gallery? You can export the `Profile` component, too. But `Gallery.js` already has a *default* export, and you can't have _two_ default exports. You could create a new file with a default export, or you could add a *named* export for `Profile`. **A file can only have one default export, but it can have numerous named exports!** - -> To reduce the potential confusion between default and named exports, some teams choose to only stick to one style (default or named), or avoid mixing them in a single file. It's a matter of preference. Do what works best for you! - -First, **export** `Profile` from `Gallery.js` using a named export (no `default` keyword): - -```js -export function Profile() { - // ... -} -``` - -Then, **import** `Profile` from `Gallery.js` to `App.js` using a named import (with the curly braces): - -```js -import { Profile } from './Gallery.js'; -``` - -Finally, **render** `` from the `App` component: - -```js -export default function App() { - return ; -} -``` - -Now `Gallery.js` contains two exports: a default `Gallery` export, and a named `Profile` export. `App.js` imports both of them. Try editing `` to `` and back in this example: - - - -```js App.js -import Gallery from './Gallery.js'; -import { Profile } from './Gallery.js'; - -export default function App() { - return ( - - ); -} -``` - -```js Gallery.js -export function Profile() { - return ( - Alan L. Hart - ); -} - -export default function Gallery() { - return ( -
-

Amazing scientists

- - - -
- ); -} -``` - -```css -img { margin: 0 10px 10px 0; height: 90px; } -``` - -
- -Now you're using a mix of default and named exports: - -* `Gallery.js`: - - Exports the `Profile` component as a **named export called `Profile`**. - - Exports the `Gallery` component as a **default export**. -* `App.js`: - - Imports `Profile` as a **named import called `Profile`** from `Gallery.js`. - - Imports `Gallery` as a **default import** from `Gallery.js`. - - Exports the root `App` component as a **default export**. - - - -On this page you learned: - -* What a root component file is -* How to import and export a component -* When and how to use default and named imports and exports -* How to export multiple components from the same file - - - - - - - -### Split the components further {/*split-the-components-further*/} - -Currently, `Gallery.js` exports both `Profile` and `Gallery`, which is a bit confusing. - -Move the `Profile` component to its own `Profile.js`, and then change the `App` component to render both `` and `` one after another. - -You may use either a default or a named export for `Profile`, but make sure that you use the corresponding import syntax in both `App.js` and `Gallery.js`! You can refer to the table from the deep dive above: - -| Syntax | Export statement | Import statement | -| ----------- | ----------- | ----------- | -| Default | `export default function Button() {}` | `import Button from './button.js';` | -| Named | `export function Button() {}` | `import { Button } from './button.js';` | - - - -Don't forget to import your components where they are called. Doesn't `Gallery` use `Profile`, too? - - - - - -```js App.js -import Gallery from './Gallery.js'; -import { Profile } from './Gallery.js'; - -export default function App() { - return ( -
- -
- ); -} -``` - -```js Gallery.js active -// Move me to Profile.js! -export function Profile() { - return ( - Alan L. Hart - ); -} - -export default function Gallery() { - return ( -
-

Amazing scientists

- - - -
- ); -} -``` - -```js Profile.js -``` - -```css -img { margin: 0 10px 10px 0; height: 90px; } -``` - -
- -After you get it working with one kind of exports, make it work with the other kind. - - - -This is the solution with named exports: - - - -```js App.js -import Gallery from './Gallery.js'; -import { Profile } from './Profile.js'; - -export default function App() { - return ( -
- - -
- ); -} -``` - -```js Gallery.js -import { Profile } from './Profile.js'; - -export default function Gallery() { - return ( -
-

Amazing scientists

- - - -
- ); -} -``` - -```js Profile.js -export function Profile() { - return ( - Alan L. Hart - ); -} -``` - -```css -img { margin: 0 10px 10px 0; height: 90px; } -``` - -
- -This is the solution with default exports: - - - -```js App.js -import Gallery from './Gallery.js'; -import Profile from './Profile.js'; - -export default function App() { - return ( -
- - -
- ); -} -``` - -```js Gallery.js -import Profile from './Profile.js'; - -export default function Gallery() { - return ( -
-

Amazing scientists

- - - -
- ); -} -``` - -```js Profile.js -export default function Profile() { - return ( - Alan L. Hart - ); -} -``` - -```css -img { margin: 0 10px 10px 0; height: 90px; } -``` - -
- -
- -
\ No newline at end of file +--- +title: Importowanie i eksportowanie komponentów +--- + + + +The magic of components lies in their reusability: you can create components that are composed of other components. But as you nest more and more components, it often makes sense to start splitting them into different files. This lets you keep your files easy to scan and reuse components in more places. + + + + + +- What a root component file is +- How to import and export a component +- When to use default and named imports and exports +- How to import and export multiple components from one file +- How to split components into multiple files + + + +## The root component file {/_the-root-component-file_/} + +In [Twój pierwszy komponent](/learn/your-first-component), you made a `Profile` component and a `Gallery` component that renders it: + + + +```js +function Profile() { + return Katherine Johnson; +} + +export default function Gallery() { + return ( +
+

Amazing scientists

+ + + +
+ ); +} +``` + +```css +img { + margin: 0 10px 10px 0; + height: 90px; +} +``` + +
+ +These currently live in a **root component file,** named `App.js` in this example. In [Create React App](https://create-react-app.dev/), your app lives in `src/App.js`. Depending on your setup, your root component could be in another file, though. If you use a framework with file-based routing, such as Next.js, your root component will be different for every page. + +## Exporting and importing a component {/_exporting-and-importing-a-component_/} + +What if you want to change the landing screen in the future and put a list of science books there? Or place all the profiles somewhere else? It makes sense to move `Gallery` and `Profile` out of the root component file. This will make them more modular and reusable in other files. You can move a component in three steps: + +1. **Make** a new JS file to put the components in. +2. **Export** your function component from that file (using either [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_the_default_export) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_named_exports) exports). +3. **Import** it in the file where you’ll use the component (using the corresponding technique for importing [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#importing_defaults) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#import_a_single_export_from_a_module) exports). + +Here both `Profile` and `Gallery` have been moved out of `App.js` into a new file called `Gallery.js`. Now you can change `App.js` to import `Gallery` from `Gallery.js`: + + + +```js App.js +import Gallery from './Gallery.js'; + +export default function App() { + return ; +} +``` + +```js Gallery.js +function Profile() { + return Alan L. Hart; +} + +export default function Gallery() { + return ( +
+

Amazing scientists

+ + + +
+ ); +} +``` + +```css +img { + margin: 0 10px 10px 0; + height: 90px; +} +``` + +
+ +Notice how this example is broken down into two component files now: + +1. `Gallery.js`: + - Defines the `Profile` component which is only used within the same file and is not exported. + - Exports the `Gallery` component as a **default export**. +2. `App.js`: + - Imports `Gallery` as a **default import** from `Gallery.js`. + - Exports the root `App` component as a **default export**. + + + +You may encounter files that leave off the `.js` file extension like so: + +```js +import Gallery from './Gallery'; +``` + +Either `'./Gallery.js'` or `'./Gallery'` will work with React, though the former is closer to how [native ES Modules](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Modules) work. + + + + + +There are two primary ways to export values with JavaScript: default exports and named exports. So far, our examples have only used default exports. But you can use one or both of them in the same file. **A file can have no more than one _default_ export, but it can have as many _named_ exports as you like.** + +![Default and named exports](/images/docs/illustrations/i_import-export.svg) + +How you export your component dictates how you must import it. You will get an error if you try to import a default export the same way you would a named export! This chart can help you keep track: + +| Syntax | Export statement | Import statement | +| ------- | ------------------------------------- | --------------------------------------- | +| Default | `export default function Button() {}` | `import Button from './button.js';` | +| Named | `export function Button() {}` | `import { Button } from './button.js';` | + +When you write a _default_ import, you can put any name you want after `import`. For example, you could write `import Banana from './button.js'` instead and it would still provide you with the same default export. In contrast, with named imports, the name has to match on both sides. That's why they are called _named_ imports! + +**People often use default exports if the file exports only one component, and use named exports if it exports multiple components and values.** Regardless of which coding style you prefer, always give meaningful names to your component functions and the files that contain them. Components without names, like `export default () => {}`, are discouraged because they make debugging harder. + + + +## Exporting and importing multiple components from the same file {/_exporting-and-importing-multiple-components-from-the-same-file_/} + +What if you want to show just one `Profile` instead of a gallery? You can export the `Profile` component, too. But `Gallery.js` already has a _default_ export, and you can't have _two_ default exports. You could create a new file with a default export, or you could add a _named_ export for `Profile`. **A file can only have one default export, but it can have numerous named exports!** + +> To reduce the potential confusion between default and named exports, some teams choose to only stick to one style (default or named), or avoid mixing them in a single file. It's a matter of preference. Do what works best for you! + +First, **export** `Profile` from `Gallery.js` using a named export (no `default` keyword): + +```js +export function Profile() { + // ... +} +``` + +Then, **import** `Profile` from `Gallery.js` to `App.js` using a named import (with the curly braces): + +```js +import {Profile} from './Gallery.js'; +``` + +Finally, **render** `` from the `App` component: + +```js +export default function App() { + return ; +} +``` + +Now `Gallery.js` contains two exports: a default `Gallery` export, and a named `Profile` export. `App.js` imports both of them. Try editing `` to `` and back in this example: + + + +```js App.js +import Gallery from './Gallery.js'; +import {Profile} from './Gallery.js'; + +export default function App() { + return ; +} +``` + +```js Gallery.js +export function Profile() { + return Alan L. Hart; +} + +export default function Gallery() { + return ( +
+

Amazing scientists

+ + + +
+ ); +} +``` + +```css +img { + margin: 0 10px 10px 0; + height: 90px; +} +``` + +
+ +Now you're using a mix of default and named exports: + +- `Gallery.js`: + - Exports the `Profile` component as a **named export called `Profile`**. + - Exports the `Gallery` component as a **default export**. +- `App.js`: + - Imports `Profile` as a **named import called `Profile`** from `Gallery.js`. + - Imports `Gallery` as a **default import** from `Gallery.js`. + - Exports the root `App` component as a **default export**. + + + +On this page you learned: + +- What a root component file is +- How to import and export a component +- When and how to use default and named imports and exports +- How to export multiple components from the same file + + + + + +### Split the components further {/_split-the-components-further_/} + +Currently, `Gallery.js` exports both `Profile` and `Gallery`, which is a bit confusing. + +Move the `Profile` component to its own `Profile.js`, and then change the `App` component to render both `` and `` one after another. + +You may use either a default or a named export for `Profile`, but make sure that you use the corresponding import syntax in both `App.js` and `Gallery.js`! You can refer to the table from the deep dive above: + +| Syntax | Export statement | Import statement | +| ------- | ------------------------------------- | --------------------------------------- | +| Default | `export default function Button() {}` | `import Button from './button.js';` | +| Named | `export function Button() {}` | `import { Button } from './button.js';` | + + + +Don't forget to import your components where they are called. Doesn't `Gallery` use `Profile`, too? + + + + + +```js App.js +import Gallery from './Gallery.js'; +import {Profile} from './Gallery.js'; + +export default function App() { + return ( +
+ +
+ ); +} +``` + +```js Gallery.js active +// Move me to Profile.js! +export function Profile() { + return Alan L. Hart; +} + +export default function Gallery() { + return ( +
+

Amazing scientists

+ + + +
+ ); +} +``` + +```js Profile.js + +``` + +```css +img { + margin: 0 10px 10px 0; + height: 90px; +} +``` + +
+ +After you get it working with one kind of exports, make it work with the other kind. + + + +This is the solution with named exports: + + + +```js App.js +import Gallery from './Gallery.js'; +import {Profile} from './Profile.js'; + +export default function App() { + return ( +
+ + +
+ ); +} +``` + +```js Gallery.js +import {Profile} from './Profile.js'; + +export default function Gallery() { + return ( +
+

Amazing scientists

+ + + +
+ ); +} +``` + +```js Profile.js +export function Profile() { + return Alan L. Hart; +} +``` + +```css +img { + margin: 0 10px 10px 0; + height: 90px; +} +``` + +
+ +This is the solution with default exports: + + + +```js App.js +import Gallery from './Gallery.js'; +import Profile from './Profile.js'; + +export default function App() { + return ( +
+ + +
+ ); +} +``` + +```js Gallery.js +import Profile from './Profile.js'; + +export default function Gallery() { + return ( +
+

Amazing scientists

+ + + +
+ ); +} +``` + +```js Profile.js +export default function Profile() { + return Alan L. Hart; +} +``` + +```css +img { + margin: 0 10px 10px 0; + height: 90px; +} +``` + +
+ +
+ +
diff --git a/beta/src/pages/learn/your-first-component.md b/beta/src/pages/learn/your-first-component.md index 1f0b271a6..a29967058 100644 --- a/beta/src/pages/learn/your-first-component.md +++ b/beta/src/pages/learn/your-first-component.md @@ -1,428 +1,424 @@ ---- -title: Your First Component ---- - - - -Components are one of the core concepts of React. They are the foundation upon which you build user interfaces (UI), which makes them the perfect place to start your React journey! - - - - - -* What a component is -* What role components play in a React application -* How to write your first React component - - - -## Components: UI building blocks {/*components-ui-building-blocks*/} - -On the Web, HTML lets us create rich structured documents with its built-in set of tags like `

` and `
  • `: - -```html -
    -

    My First Component

    -
      -
    1. Components: UI Building Blocks
    2. -
    3. Defining a Component
    4. -
    5. Using a Component
    6. -
    -
    -``` - -This markup represents this article `
    `, its heading `

    `, and an (abbreviated) table of contents as an ordered list `
      `. Markup like this, combined with CSS for style, and JavaScript for interactivity, lies behind every sidebar, avatar, modal, dropdown—every piece of UI you see on the Web. - -React lets you combine your markup, CSS, and JavaScript into custom "components," **reusable UI elements for your app.** The table of contents code you saw above could be turned into a `` component you could render on every page. Under the hood, it still uses the same HTML tags like `
      `, `

      `, etc. - -Just like with HTML tags, you can compose, order and nest components to design whole pages. For example, the documentation page you're reading is made out of React components: - -```js - - - - Docs - - - - - - - -``` - -As your project grows, you will notice that many of your designs can be composed by reusing components you already wrote, speeding up your development. Our table of contents above could be added to any screen with ``! You can even jumpstart your project with the thousands of components shared by the React open source community like [Chakra UI](https://chakra-ui.com/) and [Material UI](https://material-ui.com/). - -## Defining a component {/*defining-a-component*/} - -Traditionally when creating web pages, web developers marked up their content and then added interaction by sprinkling on some JavaScript. This worked great when interaction was a nice-to-have on the web. Now it is expected for many sites and all apps. React puts interactivity first while still using the same technology: **a React component is a JavaScript function that you can _sprinkle with markup_**. Here's what that looks like (you can edit the example below): - - - -```js -export default function Profile() { - return ( - Katherine Johnson - ) -} -``` - -```css -img { height: 200px; } -``` - - - -And here's how to build a component: - -### Step 1: Export the component {/*step-1-export-the-component*/} - -The `export default` prefix is a [standard JavaScript syntax](https://developer.mozilla.org/docs/web/javascript/reference/statements/export) (not specific to React). It lets you mark the main function in a file so that you can later import it from other files. (More on importing in [Importing and Exporting Components](/learn/importing-and-exporting-components)!) - -### Step 2: Define the function {/*step-2-define-the-function*/} - -With `function Profile() { }` you define a JavaScript function with the name `Profile`. - - - -React components are regular JavaScript functions, but **their names must start with a capital letter** or they won't work! - - - -### Step 3: Add markup {/*step-3-add-markup*/} - -The component returns an `` tag with `src` and `alt` attributes. `` is written like HTML, but it is actually JavaScript under the hood! This syntax is called [JSX](/learn/writing-markup-with-jsx), and it lets you embed markup inside JavaScript. - -Return statements can be written all on one line, as in this component: - -```js -return Katherine Johnson; -``` - -But if your markup isn't all on the same line as the return statement, you must wrap it in a pair of parentheses like this: - -```js -return ( -
      - Katherine Johnson -
      -); -``` - - - -Without parentheses, any code on the lines after `return` [will be ignored](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi)! - - - -## Using a component {/*using-a-component*/} - -Now that you've defined your `Profile` component, you can nest it inside other components. For example, you can export a `Gallery` component that uses multiple `Profile` components: - - - -```js -function Profile() { - return ( - Katherine Johnson - ); -} - -export default function Gallery() { - return ( -
      -

      Amazing scientists

      - - - -
      - ); -} -``` - -```css -img { margin: 0 10px 10px 0; height: 90px; } -``` - -
      - -### What the browser sees {/*what-the-browser-sees*/} - -Notice the difference in casing: - -* `
      ` is lowercase, so React knows we refer to an HTML tag. -* `` starts with a capital `P`, so React knows that we want to use our component called `Profile`. - -And `Profile` contains even more HTML: ``. In the end, this is what the browser sees: - -```html -
      -

      Amazing scientists

      - Katherine Johnson - Katherine Johnson - Katherine Johnson -
      -``` - -### Nesting and organizing components {/*nesting-and-organizing-components*/} - -Components are regular JavaScript functions, so you can keep multiple components in the same file. This is convenient when components are relatively small or tightly related to each other. If this file gets crowded, you can always move `Profile` to a separate file. You will learn how to do this shortly on the [page about imports](/learn/importing-and-exporting-components). - -Because the `Profile` components are rendered inside `Gallery`—even several times!—we can say that `Gallery` is a **parent component,** rendering each `Profile` as a "child". This is part of the magic of React: you can define a component once, and then use it in as many places and as many times as you like. - - - -Your React application begins at a "root" component. Usually, it is created automatically when you start a new project. For example, if you use [CodeSandbox](https://codesandbox.io/) or [Create React App](https://create-react-app.dev/), the root component is defined in `src/App.js`. If you use the framework [Next.js](https://nextjs.org/), the root component is defined in `pages/index.js`. In these examples, you've been exporting root components. - -Most React apps use components all the way down. This means that you won't only use components for reusable pieces like buttons, but also for larger pieces like sidebars, lists, and ultimately, complete pages! Components are a handy way to organize UI code and markup, even if some of them are only used once. - -Frameworks like Next.js take this a step further. Instead of using an empty HTML file and letting React "take over" managing the page with JavaScript, they *also* generate the HTML automatically from your React components. This allows your app to show some content before the JavaScript code loads. - -Still, many websites only use React to [add "sprinkles of interactivity"](/learn/add-react-to-a-website). They have many root components instead of a single one for the entire page. You can use as much—or as little—React as you need. - - - - - -You've just gotten your first taste of React! Let's recap some key points. - -* React lets you create components, **reusable UI elements for your app.** -* In a React app, every piece of UI is a component. -* React components are regular JavaScript functions except: - - 1. Their names always begin with a capital letter. - 2. They return JSX markup. - - - - - - - -### Export the component {/*export-the-component*/} - -This sandbox doesn't work because the root component is not exported: - - - -```js -function Profile() { - return ( - Aklilu Lemma - ); -} -``` - -```css -img { height: 181px; } -``` - - - -Try to fix it yourself before looking at the solution! - - - -Add `export default` before the function definition like so: - - - -```js -export default function Profile() { - return ( - Aklilu Lemma - ); -} -``` - -```css -img { height: 181px; } -``` - - - -You might be wondering why writing `export` alone is not enough to fix this example. You can learn the difference between `export` and `export default` in [Importing and Exporting Components](/learn/importing-and-exporting-components). - - - -### Fix the return statement {/*fix-the-return-statement*/} - -Something isn't right about this `return` statement. Can you fix it? - - - -You may get an "Unexpected token" error while trying to fix this. In that case, check the that semicolon appears *after* the closing parenthesis. Leaving a semicolon inside `return ( )` will cause an error. - - - - - - -```js -export default function Profile() { - return - Katsuko Saruhashi; -} -``` - -```css -img { height: 180px; } -``` - - - - - -You can fix this component by moving the return statement to one line like so: - - - -```js -export default function Profile() { - return Katsuko Saruhashi; -} -``` - -```css -img { height: 180px; } -``` - - - -Or by wrapping the returned JSX markup in parentheses that open right after `return`: - - - -```js -export default function Profile() { - return ( - Katsuko Saruhashi - ); -} -``` - -```css -img { height: 180px; } -``` - - - - - -### Spot the mistake {/*spot-the-mistake*/} - -Something's wrong with how the `Profile` component is declared and used. Can you spot the mistake? (Try to remember how React distinguishes components from the regular HTML tags!) - - - -```js -function profile() { - return ( - Alan L. Hart - ); -} - -export default function Gallery() { - return ( -
      -

      Amazing scientists

      - - - -
      - ); -} -``` - -```css -img { margin: 0 10px 10px 0; height: 90px; } -``` - -
      - - - -React component names must start with a capital letter. - -Change `function profile()` to `function Profile()`, and then change every `` to ``: - - - -```js -function Profile() { - return ( - Alan L. Hart - ); -} - -export default function Gallery() { - return ( -
      -

      Amazing scientists

      - - - -
      - ); -} -``` - -```css -img { margin: 0 10px 10px 0; } -``` - -
      - -
      - -### Your own component {/*your-own-component*/} - -Write a component from scratch. You can give it any valid name and return any markup. If you're out of ideas, you can write a `Congratulations` component thats shows `

      Good job!

      `. Don't forget to export it! - - - -```js -// Write your component below! - -``` - - - - - - - -```js -export default function Congratulations() { - return ( -

      Good job!

      - ); -} -``` - -
      - -
      - -
      \ No newline at end of file +--- +title: Twój pierwszy komponent +--- + + + +Komponent jest jednym z podstawowych pojęć w świecie Reacta. Jest bazą, na której buduje się interfejsy użytkownika (UI), przez co idealnie nadaje się na pierwszy temat do nauki! + + + + + +- Czym jest komponent? +- Jaką rolę komponenty odgrywają w aplikacji reactowej? +- Jak napisać swój pierwszy komponent? + + + +## Komponenty: cegiełki do budowania UI-a {/_components-ui-building-blocks_/} + +W świecie aplikacji internetowych HTML pozwala nam na tworzenie dokumentów o bogatej strukturze przy pomocy wbudowanych znaczników, jak `

      ` czy `
    1. `: + +```html +
      +

      Twój pierwszy komponent

      +
        +
      1. Komponenty: cegiełki do budowania UI
      2. +
      3. Definiowanie komponentu
      4. +
      5. Używanie komponentu
      6. +
      +
      +``` + +Powyższy kod odzwierciedla czytany przez ciebie artykuł `
      `, jego nagłówek `

      ` i (skrócony) spis treści w postaci listy numerowanej `
        `. Tego typu kod, połączony ze stylami CSS oraz interaktywnością napisaną w JavaScripcie, stoi za każdym paskiem bocznym, awatarem, oknem dialogowym, listą rozwijaną - każdym fragmentem UI-a widocznym w sieci. + +React pozwala na połączenie znaczników, CSS-a i JavaScriptu w "komponent", **element wielokrotnego użytku stanowiący część UI-a twojej aplikacji.** Powyższy kod, reprezentujący spis treści, mógłby zostać zastąpiony komponentem ``, renderowanym na każdej stronie. Pod spodem nadal byłby to ten sam kod HTML, składający się z `
        `, `

        ` itd. + +Podobnie jak w przypadku znaczników HTML-owych, komponenty można łączyć, zagnieżdżać i zmieniać im kolejność, tworząc w ten sposób całe strony. Dla przykładu, dokumentacja, którą właśnie czytasz, składa się z następujących komponentów: + +```js + + + + Dokumentacja + + + + + + + +``` + +Wraz ze wzrostem złożoności projektu z pewnością zauważysz, że wiele widoków można poskładać z istniejących już komponentów, co znacznie skróci czas pisania kodu. Nasz spis treści mógłby być dodawany do każdej strony jako ``! Co więcej, możesz rozpędzić prace nad aplikacją korzystając z tysięcy komponentów udostępnianych przez reactową społeczność open-source'ową, takich jak [Chakra UI](https://chakra-ui.com/) czy [Material UI](https://material-ui.com/). + +## Definiowanie komponentu {/_defining-a-component_/} + +W przeszłości, kiedy programiści tworzyli stronę internetową, składali najpierw HTML, aby zbudować treść, a następnie dokładali kod javascriptowy dodający interakcje. Takie podejście działało, gdy interakcje na stronie były tylko przyjemnym dodatkiem; teraz dla wielu stron jest to mus. React stawia interakcje na pierwszym miejscu, w dalszym ciągu korzystając z tej samej technologii: **komponent reactowy jest więc funkcją javascriptową _okraszony znacznikami_**. Oto przykład, jak to może wyglądać w rzeczywistości (poniższy kod można edytować): + + + +```js +export default function Profile() { + return ( + Katherine Johnson + ) +} +``` + +```css +img { height: 200px; } +``` + + + +A oto przepis na stworzenie komponentu: + +### Krok 1: Wyeksportuj komponent {/_step-1-export-the-component_/} + +Prefiks `export default` należy do [standardowej składni JavaScriptu](https://developer.mozilla.org/docs/web/javascript/reference/statements/export) (nie jest specyficzny dla samego Reacta). Pozwala oznaczyć funkcję tak, aby można było ją zaimportować w innych plikach. (Więcej na temat importowania dowiesz się z rozdziału pt. [Importowanie i eksportowanie komponentów](/learn/importing-and-exporting-components)!) + +### Krok 2: Zdefiniuj funkcję {/_step-2-define-the-function_/} + +Za pomocą `function Profile() { }` definiujemy funkcję javascriptową o nazwie `Profile`. + + + +Komponenty reactowe są zwykłymi funkcjami javascriptowymi, lecz **ich nazwy muszą naczynać od wiekiej litery**. W przeciwnym razie nie będą działać! + + + +### Krok 3: Dodaj kod {/_step-3-add-markup_/} + +Komponent zwraca znacznik `` z atrybutami `src` oraz `alt`. `` jest napisany jak w HTML-u, lecz tak naprawdę pod spodem wykonuje się kod javascriptowy! Ta składnia nosi nazwę [JSX](/learn/writing-markup-with-jsx) i pozwala umieszczać znaczniki w kodzie javascriptowym. + +Instrukcje wyjścia (_ang._ return statements) mogą być napisane w jednej linii, jak w poniższym przykładzie: + +```js +return Katherine Johnson; +``` + +lecz jeśli znaczniki nie znajdują się w tej samej linii co instrukcja wyjścia, musisz otoczyć je parą nawiasów: + +```js +return ( +
        + Katherine Johnson +
        +); +``` + + + +Jeśli nie dodasz nawiasów, kod zawarty w kolejnych liniach po `return` [zostanie zignorowany](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi)! + + + +## Używanie komponentu {/_using-a-component_/} + +Teraz gdy masz już zdefiniowany komponent `Profile`, możesz zagnieździć go w innych komponentach. Na przykład, możesz wyeksportować komponent `Gallery`, który wyświetla kilka komponentów `Profile`: + + + +```js +function Profile() { + return ( + Katherine Johnson + ); +} + +export default function Gallery() { + return ( +
        +

        Niesamowici naukowcy

        + + + +
        + ); +} +``` + +```css +img { margin: 0 10px 10px 0; height: 90px; } +``` + +
        + +### Co widzi przeglądarka {/_what-the-browser-sees_/} + +Zauważ różnicę w wielkości liter: + +- `
        ` zaczyna się od małej litery, dzięki czemu React wie, że mamy na myśli znacznik HTML-owy. +- `` zaczyna się od wielkiej litery `P`, stąd React wie, że mamy na myśli komponent o nazwie `Profile`. + +A sam `Profile` zawiera jeszcze więcej kodu HTML: ``. Ostatecznie, to, co trafia do przeglądarki, to: + +```html +
        +

        Niesamowici naukowcy

        + Katherine Johnson + Katherine Johnson + Katherine Johnson +
        +``` + +### Zagnieżdżanie i rozmieszczanie komponentów {/_nesting-and-organizing-components_/} + +Komponenty są zwykłymi funkcjami javascriptowymi, dzięki czemu możesz mieć kilka komponentów w tym samym pliku. Jest to wygodne, gdy komponenty są małe lub mocno ze sobą powiązane. Jeśli jednak plik zacznie robić się długi i skomplikowany, zawsze możesz przenieść `Profile` do osobnego pliku. Wkrótce dowiesz się, jak to zrobić, na [stronie o importach](/learn/importing-and-exporting-components). + +Ponieważ komponenty `Profile` są renderowane wewnątrz `Gallery` — nawet kilka razy! — możemy powiedzieć, że `Gallery` jest **komponentem-rodzicem** (nadrzędnym), a każdy z `Profile` jest "dzieckiem" (potomkiem). Na tym właśnie polega magia Reacta: możesz zdefiniować komponent jeden raz, a używać go wielokrotnie w wielu miejscach. + + + +Twoja aplikacja reactowa zaczyna się w komponencie głównym (_ang._ root - "korzeń"). Zwykle jest on tworzony automatycznie przy starcie nowego projektu. Na przykład, jeśli używasz [CodeSandbox](https://codesandbox.io/) lub [Create React App](https://create-react-app.dev/), komponent główny jest zdefiniowany w pliku `src/App.js`. Jeśli używasz frameworka [Next.js](https://nextjs.org/), komponent główny jest zdefiniowany w pliku `pages/index.js`. W poprzednich przykładach eksportowaliśmy własne komponenty główne. + +Większość aplikacji reactowych używa komponentów "od góry do dołu". Oznacza to, że nie tylko fragmenty wielokrotnego użytku, jak przyciski, stają się komponentami, lecz także większe kawałki interfejsu, jak paski boczne, listy czy nawet całe strony! Komponenty doskonale sprawdzają się w porządkowaniu kodu UI, nawet jeśli niektórych z nich używamy tylko jeden raz. + +Frameworki takie jak Next.js idą o krok dalej. Zamiast tworzyć pusty plik HTML i pozwolić Reactowi "przejąć kontrolę" nad stroną poprzez JavaScript, niektóre frameworki _również_ automatycznie generują kod HTML z komponentów. Umożliwia to wyświetlenie choć części treści strony, podczas gdy kod javascriptowy jest ładowany. + +Mimo wszystko wiele stron używa Reacta tylko po to, by [dodać do nich "szczyptę interaktywności"](/learn/add-react-to-a-website). Mają one wiele komponentów głównych zamiast jednego na całą stronę. Świadczy to o tym, że Reacta można używać w takim stopniu, jaki jest aktualnie potrzebny. + + + + + +Masz za sobą przedsmak tego, co potrafi React! Zróbmy małe podsumowanie. + +- React umożliwia tworzenie komponentów - **elementów wielokrotnego użytku stanowiących fragmenty UI-a twojej aplikacji.** +- W aplikacji reactowej każdy kawałek interfejsu użytkownika jest komponentem. +- Komponenty reactowe są zwykłymi funkcjami javascriptowymi, przy czym: + + 1. Ich nazwa musi zaczynać się od wielkiej litery. + 2. Zwracają kod JSX. + + + + + +### Wyeksportuj komponent {/_export-the-component_/} + +Poniższy sandbox nie działa, ponieważ główny komponent nie jest wyeksportowany: + + + +```js +function Profile() { + return ( + Aklilu Lemma + ); +} +``` + +```css +img { height: 181px; } +``` + + + +Spróbuj naprawić błąd samodzielnie, zanim zajrzyjsz do rozwiązania! + + + +Dodaj prefiks `export default` przed definicją funkcji: + + + +```js +export default function Profile() { + return ( + Aklilu Lemma + ); +} +``` + +```css +img { height: 181px; } +``` + + + +Być może zastanawiasz się, dlaczego nie wystarczyło napisać `export`? Różnice pomiędzy `export` a `export default` opisaliśmy w rozdziale pt. [Importowanie i eksportowanie komponentów](/learn/importing-and-exporting-components). + + + +### Napraw zwracaną wartość {/_fix-the-return-statement_/} + +Coś jest nie tak z tą instrukcją `return`. Potrafisz to naprawić? + + + +Podczas naprawiania tego błędu możesz natknąć się na błąd "Unexpected token". W takim wypadku upewnij się, że średnik znajduje się _po_ nawiasie zamykającym. Jeśli średnik znajdzie się wewnątrz `return ( )`, otrzymasz błąd. + + + + + +```js +export default function Profile() { + return + Katsuko Saruhashi; +} +``` + +```css +img { height: 180px; } +``` + + + + + +Możesz naprawić ten komponent przesuwając całe zwracane wyrażenie do jednej linii: + + + +```js +export default function Profile() { + return Katsuko Saruhashi; +} +``` + +```css +img { height: 180px; } +``` + + + +Lub otaczając zwracany kod JSX parą nawiasów, która otwiera się za słowem `return`: + + + +```js +export default function Profile() { + return ( + Katsuko Saruhashi + ); +} +``` + +```css +img { height: 180px; } +``` + + + + + +### Znajdź pomyłkę {/_spot-the-mistake_/} + +Coś jest nie tak z definicją i użyciem komponentu `Profile`. Potrafisz znaleźć pomyłkę? (Spróbuj przypomnieć sobie, jak React odróżnia komponenty od zwykłych znaczników HTML-owych!) + + + +```js +function profile() { + return ( + Alan L. Hart + ); +} + +export default function Gallery() { + return ( +
        +

        Niesamowici naukowcy

        + + + +
        + ); +} +``` + +```css +img { margin: 0 10px 10px 0; height: 90px; } +``` + +
        + + + +Nazwy komponentów reactowych muszą zaczynać się od wielkiej litery. + +Zmień `function profile()` na `function Profile()`, a następnie każde `` na ``: + + + +```js +function Profile() { + return ( + Alan L. Hart + ); +} + +export default function Gallery() { + return ( +
        +

        Niesamowici naukowcy

        + + + +
        + ); +} +``` + +```css +img { margin: 0 10px 10px 0; } +``` + +
        + +
        + +### Napisz swój własny komponent {/_your-own-component_/} + +Napisz komponent od zera. Możesz nadać mu dowolną poprawną nazwę i zwrócić dowolną strukturę znaczników. Jeśli brakuje ci pomysłów, stwórz komponent `Congratulations`, który wyświetla `

        Dobra robota!

        `. Nie zapomnij go wyeksportować! + + + +```js +// Napisz tutaj swój komponent! +``` + + + + + + + +```js +export default function Congratulations() { + return ( +

        Dobra robota!

        + ) +} +``` + +
        + +
        + +
        diff --git a/beta/src/sidebarLearn.json b/beta/src/sidebarLearn.json index 90b39ed77..75e59b45d 100644 --- a/beta/src/sidebarLearn.json +++ b/beta/src/sidebarLearn.json @@ -43,11 +43,11 @@ "path": "/learn/describing-the-ui", "routes": [ { - "title": "Your First Component", + "title": "Twój pierwszy komponent", "path": "/learn/your-first-component" }, { - "title": "Importing and Exporting Components", + "title": "Importowanie i eksportowanie komponentów", "path": "/learn/importing-and-exporting-components" }, { From babe5381031318347162c339f5d17577d3a56c54 Mon Sep 17 00:00:00 2001 From: Jakub Drozdek Date: Fri, 3 Dec 2021 01:04:29 +0100 Subject: [PATCH 2/2] Revert formatting in "importing and exporting components" --- .../importing-and-exporting-components.md | 814 +++++++++--------- 1 file changed, 416 insertions(+), 398 deletions(-) diff --git a/beta/src/pages/learn/importing-and-exporting-components.md b/beta/src/pages/learn/importing-and-exporting-components.md index 8f5a7ebd8..7ace296cf 100644 --- a/beta/src/pages/learn/importing-and-exporting-components.md +++ b/beta/src/pages/learn/importing-and-exporting-components.md @@ -1,398 +1,416 @@ ---- -title: Importowanie i eksportowanie komponentów ---- - - - -The magic of components lies in their reusability: you can create components that are composed of other components. But as you nest more and more components, it often makes sense to start splitting them into different files. This lets you keep your files easy to scan and reuse components in more places. - - - - - -- What a root component file is -- How to import and export a component -- When to use default and named imports and exports -- How to import and export multiple components from one file -- How to split components into multiple files - - - -## The root component file {/_the-root-component-file_/} - -In [Twój pierwszy komponent](/learn/your-first-component), you made a `Profile` component and a `Gallery` component that renders it: - - - -```js -function Profile() { - return Katherine Johnson; -} - -export default function Gallery() { - return ( -
        -

        Amazing scientists

        - - - -
        - ); -} -``` - -```css -img { - margin: 0 10px 10px 0; - height: 90px; -} -``` - -
        - -These currently live in a **root component file,** named `App.js` in this example. In [Create React App](https://create-react-app.dev/), your app lives in `src/App.js`. Depending on your setup, your root component could be in another file, though. If you use a framework with file-based routing, such as Next.js, your root component will be different for every page. - -## Exporting and importing a component {/_exporting-and-importing-a-component_/} - -What if you want to change the landing screen in the future and put a list of science books there? Or place all the profiles somewhere else? It makes sense to move `Gallery` and `Profile` out of the root component file. This will make them more modular and reusable in other files. You can move a component in three steps: - -1. **Make** a new JS file to put the components in. -2. **Export** your function component from that file (using either [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_the_default_export) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_named_exports) exports). -3. **Import** it in the file where you’ll use the component (using the corresponding technique for importing [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#importing_defaults) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#import_a_single_export_from_a_module) exports). - -Here both `Profile` and `Gallery` have been moved out of `App.js` into a new file called `Gallery.js`. Now you can change `App.js` to import `Gallery` from `Gallery.js`: - - - -```js App.js -import Gallery from './Gallery.js'; - -export default function App() { - return ; -} -``` - -```js Gallery.js -function Profile() { - return Alan L. Hart; -} - -export default function Gallery() { - return ( -
        -

        Amazing scientists

        - - - -
        - ); -} -``` - -```css -img { - margin: 0 10px 10px 0; - height: 90px; -} -``` - -
        - -Notice how this example is broken down into two component files now: - -1. `Gallery.js`: - - Defines the `Profile` component which is only used within the same file and is not exported. - - Exports the `Gallery` component as a **default export**. -2. `App.js`: - - Imports `Gallery` as a **default import** from `Gallery.js`. - - Exports the root `App` component as a **default export**. - - - -You may encounter files that leave off the `.js` file extension like so: - -```js -import Gallery from './Gallery'; -``` - -Either `'./Gallery.js'` or `'./Gallery'` will work with React, though the former is closer to how [native ES Modules](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Modules) work. - - - - - -There are two primary ways to export values with JavaScript: default exports and named exports. So far, our examples have only used default exports. But you can use one or both of them in the same file. **A file can have no more than one _default_ export, but it can have as many _named_ exports as you like.** - -![Default and named exports](/images/docs/illustrations/i_import-export.svg) - -How you export your component dictates how you must import it. You will get an error if you try to import a default export the same way you would a named export! This chart can help you keep track: - -| Syntax | Export statement | Import statement | -| ------- | ------------------------------------- | --------------------------------------- | -| Default | `export default function Button() {}` | `import Button from './button.js';` | -| Named | `export function Button() {}` | `import { Button } from './button.js';` | - -When you write a _default_ import, you can put any name you want after `import`. For example, you could write `import Banana from './button.js'` instead and it would still provide you with the same default export. In contrast, with named imports, the name has to match on both sides. That's why they are called _named_ imports! - -**People often use default exports if the file exports only one component, and use named exports if it exports multiple components and values.** Regardless of which coding style you prefer, always give meaningful names to your component functions and the files that contain them. Components without names, like `export default () => {}`, are discouraged because they make debugging harder. - - - -## Exporting and importing multiple components from the same file {/_exporting-and-importing-multiple-components-from-the-same-file_/} - -What if you want to show just one `Profile` instead of a gallery? You can export the `Profile` component, too. But `Gallery.js` already has a _default_ export, and you can't have _two_ default exports. You could create a new file with a default export, or you could add a _named_ export for `Profile`. **A file can only have one default export, but it can have numerous named exports!** - -> To reduce the potential confusion between default and named exports, some teams choose to only stick to one style (default or named), or avoid mixing them in a single file. It's a matter of preference. Do what works best for you! - -First, **export** `Profile` from `Gallery.js` using a named export (no `default` keyword): - -```js -export function Profile() { - // ... -} -``` - -Then, **import** `Profile` from `Gallery.js` to `App.js` using a named import (with the curly braces): - -```js -import {Profile} from './Gallery.js'; -``` - -Finally, **render** `` from the `App` component: - -```js -export default function App() { - return ; -} -``` - -Now `Gallery.js` contains two exports: a default `Gallery` export, and a named `Profile` export. `App.js` imports both of them. Try editing `` to `` and back in this example: - - - -```js App.js -import Gallery from './Gallery.js'; -import {Profile} from './Gallery.js'; - -export default function App() { - return ; -} -``` - -```js Gallery.js -export function Profile() { - return Alan L. Hart; -} - -export default function Gallery() { - return ( -
        -

        Amazing scientists

        - - - -
        - ); -} -``` - -```css -img { - margin: 0 10px 10px 0; - height: 90px; -} -``` - -
        - -Now you're using a mix of default and named exports: - -- `Gallery.js`: - - Exports the `Profile` component as a **named export called `Profile`**. - - Exports the `Gallery` component as a **default export**. -- `App.js`: - - Imports `Profile` as a **named import called `Profile`** from `Gallery.js`. - - Imports `Gallery` as a **default import** from `Gallery.js`. - - Exports the root `App` component as a **default export**. - - - -On this page you learned: - -- What a root component file is -- How to import and export a component -- When and how to use default and named imports and exports -- How to export multiple components from the same file - - - - - -### Split the components further {/_split-the-components-further_/} - -Currently, `Gallery.js` exports both `Profile` and `Gallery`, which is a bit confusing. - -Move the `Profile` component to its own `Profile.js`, and then change the `App` component to render both `` and `` one after another. - -You may use either a default or a named export for `Profile`, but make sure that you use the corresponding import syntax in both `App.js` and `Gallery.js`! You can refer to the table from the deep dive above: - -| Syntax | Export statement | Import statement | -| ------- | ------------------------------------- | --------------------------------------- | -| Default | `export default function Button() {}` | `import Button from './button.js';` | -| Named | `export function Button() {}` | `import { Button } from './button.js';` | - - - -Don't forget to import your components where they are called. Doesn't `Gallery` use `Profile`, too? - - - - - -```js App.js -import Gallery from './Gallery.js'; -import {Profile} from './Gallery.js'; - -export default function App() { - return ( -
        - -
        - ); -} -``` - -```js Gallery.js active -// Move me to Profile.js! -export function Profile() { - return Alan L. Hart; -} - -export default function Gallery() { - return ( -
        -

        Amazing scientists

        - - - -
        - ); -} -``` - -```js Profile.js - -``` - -```css -img { - margin: 0 10px 10px 0; - height: 90px; -} -``` - -
        - -After you get it working with one kind of exports, make it work with the other kind. - - - -This is the solution with named exports: - - - -```js App.js -import Gallery from './Gallery.js'; -import {Profile} from './Profile.js'; - -export default function App() { - return ( -
        - - -
        - ); -} -``` - -```js Gallery.js -import {Profile} from './Profile.js'; - -export default function Gallery() { - return ( -
        -

        Amazing scientists

        - - - -
        - ); -} -``` - -```js Profile.js -export function Profile() { - return Alan L. Hart; -} -``` - -```css -img { - margin: 0 10px 10px 0; - height: 90px; -} -``` - -
        - -This is the solution with default exports: - - - -```js App.js -import Gallery from './Gallery.js'; -import Profile from './Profile.js'; - -export default function App() { - return ( -
        - - -
        - ); -} -``` - -```js Gallery.js -import Profile from './Profile.js'; - -export default function Gallery() { - return ( -
        -

        Amazing scientists

        - - - -
        - ); -} -``` - -```js Profile.js -export default function Profile() { - return Alan L. Hart; -} -``` - -```css -img { - margin: 0 10px 10px 0; - height: 90px; -} -``` - -
        - -
        - -
        +--- +title: Importowanie i eksportowanie komponentów +--- + + + +The magic of components lies in their reusability: you can create components that are composed of other components. But as you nest more and more components, it often makes sense to start splitting them into different files. This lets you keep your files easy to scan and reuse components in more places. + + + + + +* What a root component file is +* How to import and export a component +* When to use default and named imports and exports +* How to import and export multiple components from one file +* How to split components into multiple files + + + +## The root component file {/*the-root-component-file*/} + +In [Twój pierwszy komponent](/learn/your-first-component), you made a `Profile` component and a `Gallery` component that renders it: + + + +```js +function Profile() { + return ( + Katherine Johnson + ); +} + +export default function Gallery() { + return ( +
        +

        Amazing scientists

        + + + +
        + ); +} +``` + +```css +img { margin: 0 10px 10px 0; height: 90px; } +``` + +
        + +These currently live in a **root component file,** named `App.js` in this example. In [Create React App](https://create-react-app.dev/), your app lives in `src/App.js`. Depending on your setup, your root component could be in another file, though. If you use a framework with file-based routing, such as Next.js, your root component will be different for every page. + +## Exporting and importing a component {/*exporting-and-importing-a-component*/} + +What if you want to change the landing screen in the future and put a list of science books there? Or place all the profiles somewhere else? It makes sense to move `Gallery` and `Profile` out of the root component file. This will make them more modular and reusable in other files. You can move a component in three steps: + +1. **Make** a new JS file to put the components in. +2. **Export** your function component from that file (using either [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_the_default_export) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/export#using_named_exports) exports). +3. **Import** it in the file where you’ll use the component (using the corresponding technique for importing [default](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#importing_defaults) or [named](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import#import_a_single_export_from_a_module) exports). + +Here both `Profile` and `Gallery` have been moved out of `App.js` into a new file called `Gallery.js`. Now you can change `App.js` to import `Gallery` from `Gallery.js`: + + + +```js App.js +import Gallery from './Gallery.js'; + +export default function App() { + return ( + + ); +} +``` + +```js Gallery.js +function Profile() { + return ( + Alan L. Hart + ); +} + +export default function Gallery() { + return ( +
        +

        Amazing scientists

        + + + +
        + ); +} +``` + +```css +img { margin: 0 10px 10px 0; height: 90px; } +``` + +
        + +Notice how this example is broken down into two component files now: + +1. `Gallery.js`: + - Defines the `Profile` component which is only used within the same file and is not exported. + - Exports the `Gallery` component as a **default export**. +2. `App.js`: + - Imports `Gallery` as a **default import** from `Gallery.js`. + - Exports the root `App` component as a **default export**. + + + + +You may encounter files that leave off the `.js` file extension like so: + +```js +import Gallery from './Gallery'; +``` + +Either `'./Gallery.js'` or `'./Gallery'` will work with React, though the former is closer to how [native ES Modules](https://developer.mozilla.org/docs/Web/JavaScript/Guide/Modules) work. + + + + + +There are two primary ways to export values with JavaScript: default exports and named exports. So far, our examples have only used default exports. But you can use one or both of them in the same file. **A file can have no more than one _default_ export, but it can have as many _named_ exports as you like.** + +![Default and named exports](/images/docs/illustrations/i_import-export.svg) + +How you export your component dictates how you must import it. You will get an error if you try to import a default export the same way you would a named export! This chart can help you keep track: + +| Syntax | Export statement | Import statement | +| ----------- | ----------- | ----------- | +| Default | `export default function Button() {}` | `import Button from './button.js';` | +| Named | `export function Button() {}` | `import { Button } from './button.js';` | + +When you write a _default_ import, you can put any name you want after `import`. For example, you could write `import Banana from './button.js'` instead and it would still provide you with the same default export. In contrast, with named imports, the name has to match on both sides. That's why they are called _named_ imports! + +**People often use default exports if the file exports only one component, and use named exports if it exports multiple components and values.** Regardless of which coding style you prefer, always give meaningful names to your component functions and the files that contain them. Components without names, like `export default () => {}`, are discouraged because they make debugging harder. + + + +## Exporting and importing multiple components from the same file {/*exporting-and-importing-multiple-components-from-the-same-file*/} + +What if you want to show just one `Profile` instead of a gallery? You can export the `Profile` component, too. But `Gallery.js` already has a *default* export, and you can't have _two_ default exports. You could create a new file with a default export, or you could add a *named* export for `Profile`. **A file can only have one default export, but it can have numerous named exports!** + +> To reduce the potential confusion between default and named exports, some teams choose to only stick to one style (default or named), or avoid mixing them in a single file. It's a matter of preference. Do what works best for you! + +First, **export** `Profile` from `Gallery.js` using a named export (no `default` keyword): + +```js +export function Profile() { + // ... +} +``` + +Then, **import** `Profile` from `Gallery.js` to `App.js` using a named import (with the curly braces): + +```js +import { Profile } from './Gallery.js'; +``` + +Finally, **render** `` from the `App` component: + +```js +export default function App() { + return ; +} +``` + +Now `Gallery.js` contains two exports: a default `Gallery` export, and a named `Profile` export. `App.js` imports both of them. Try editing `` to `` and back in this example: + + + +```js App.js +import Gallery from './Gallery.js'; +import { Profile } from './Gallery.js'; + +export default function App() { + return ( + + ); +} +``` + +```js Gallery.js +export function Profile() { + return ( + Alan L. Hart + ); +} + +export default function Gallery() { + return ( +
        +

        Amazing scientists

        + + + +
        + ); +} +``` + +```css +img { margin: 0 10px 10px 0; height: 90px; } +``` + +
        + +Now you're using a mix of default and named exports: + +* `Gallery.js`: + - Exports the `Profile` component as a **named export called `Profile`**. + - Exports the `Gallery` component as a **default export**. +* `App.js`: + - Imports `Profile` as a **named import called `Profile`** from `Gallery.js`. + - Imports `Gallery` as a **default import** from `Gallery.js`. + - Exports the root `App` component as a **default export**. + + + +On this page you learned: + +* What a root component file is +* How to import and export a component +* When and how to use default and named imports and exports +* How to export multiple components from the same file + + + + + + + +### Split the components further {/*split-the-components-further*/} + +Currently, `Gallery.js` exports both `Profile` and `Gallery`, which is a bit confusing. + +Move the `Profile` component to its own `Profile.js`, and then change the `App` component to render both `` and `` one after another. + +You may use either a default or a named export for `Profile`, but make sure that you use the corresponding import syntax in both `App.js` and `Gallery.js`! You can refer to the table from the deep dive above: + +| Syntax | Export statement | Import statement | +| ----------- | ----------- | ----------- | +| Default | `export default function Button() {}` | `import Button from './button.js';` | +| Named | `export function Button() {}` | `import { Button } from './button.js';` | + + + +Don't forget to import your components where they are called. Doesn't `Gallery` use `Profile`, too? + + + + + +```js App.js +import Gallery from './Gallery.js'; +import { Profile } from './Gallery.js'; + +export default function App() { + return ( +
        + +
        + ); +} +``` + +```js Gallery.js active +// Move me to Profile.js! +export function Profile() { + return ( + Alan L. Hart + ); +} + +export default function Gallery() { + return ( +
        +

        Amazing scientists

        + + + +
        + ); +} +``` + +```js Profile.js +``` + +```css +img { margin: 0 10px 10px 0; height: 90px; } +``` + +
        + +After you get it working with one kind of exports, make it work with the other kind. + + + +This is the solution with named exports: + + + +```js App.js +import Gallery from './Gallery.js'; +import { Profile } from './Profile.js'; + +export default function App() { + return ( +
        + + +
        + ); +} +``` + +```js Gallery.js +import { Profile } from './Profile.js'; + +export default function Gallery() { + return ( +
        +

        Amazing scientists

        + + + +
        + ); +} +``` + +```js Profile.js +export function Profile() { + return ( + Alan L. Hart + ); +} +``` + +```css +img { margin: 0 10px 10px 0; height: 90px; } +``` + +
        + +This is the solution with default exports: + + + +```js App.js +import Gallery from './Gallery.js'; +import Profile from './Profile.js'; + +export default function App() { + return ( +
        + + +
        + ); +} +``` + +```js Gallery.js +import Profile from './Profile.js'; + +export default function Gallery() { + return ( +
        +

        Amazing scientists

        + + + +
        + ); +} +``` + +```js Profile.js +export default function Profile() { + return ( + Alan L. Hart + ); +} +``` + +```css +img { margin: 0 10px 10px 0; height: 90px; } +``` + +
        + +
        + +
        \ No newline at end of file