Skip to content

Convert 2 examples to CodeSandbox #138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 15 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions content/docs/portals.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ A typical use case for portals is when a parent component has an `overflow: hidd
>
> It is important to remember, when working with portals, you'll need to make sure to follow the proper accessibility guidelines.

[Try it on CodePen.](https://codepen.io/gaearon/pen/yzMaBd)
[Try it on CodeSandbox.](https://codesandbox.io/embed/github/CompuIves/reactjs.org/tree/codesandbox/examples/portals-1?codemirror=1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be nice to bundle this up as a custom remark transform. That way we could keep the query params and stuff in one place, and just write Markdown like:

[Try it on CodeSandbox](codesandbox=examples/portals-1)

Edit Looks like this would be similar to the "Run Example" markdown below 👍

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mentioned this because I was wondering if we could, for example, auto-expand the left side menu on multi-file examples b'c it's not obvious there is more than one file when you open a new sandbox- and it would be nice to not have to find-and-replace a bunch of links to do this.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could also have the same issue I mentioned below though, of being difficult to test initially (at least for a reviewer).


## Event Bubbling Through Portals

Expand Down Expand Up @@ -139,6 +139,6 @@ function Child() {
ReactDOM.render(<Parent />, appRoot);
```

[Try it on CodePen.](https://codepen.io/gaearon/pen/jGBWpE)
[Try it on CodeSandbox.](https://codesandbox.io/embed/github/CompuIves/reactjs.org/tree/codesandbox/examples/portals-2?codemirror=1)

Catching an event bubbling up from a portal in a parent component allows the development of more flexible abstractions that are not inherently reliant on portals. For example, if you render a `<Modal />` component, the parent can capture its events regardless of whether it's implemented using portals.
150 changes: 7 additions & 143 deletions content/docs/state-and-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,50 +13,13 @@ So far we have only learned one way to update the UI.

We call `ReactDOM.render()` to change the rendered output:

```js{8-11}
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(
element,
document.getElementById('root')
);
}

setInterval(tick, 1000);
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/gwoJZk?editors=0010)
[Run example.](source:examples/single-file-examples/src/state-and-lifecycle/state-and-lifecycle-1.js{11}?editorsize=70&forcerefresh=1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm. Just tried this one locally and it failed:

Failed to load resource: the server responded with a status of 422 ()
GET https://codesandbox.io/api/v1/sandboxes/github/reactjs/reactjs.org/tree/codesandbox/examples/single-file-examples/src/state-and-lifecycle/state-and-lifecycle-1.js

I think that's because the code it's trying to open only exists on your fork of the repo.

This default behavior would make things hard to test for people adding new runnable examples though?


In this section, we will learn how to make the `Clock` component truly reusable and encapsulated. It will set up its own timer and update itself every second.

We can start by encapsulating how the clock looks:

```js{3-6,12}
function Clock(props) {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {props.date.toLocaleTimeString()}.</h2>
</div>
);
}

function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('root')
);
}

setInterval(tick, 1000);
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/dpdoYR?editors=0010)
[Run example.](source:examples/single-file-examples/src/state-and-lifecycle/state-and-lifecycle-2.js{6,7,8,9,14}?editorsize=70&forcerefresh=1)

However, it misses a crucial requirement: the fact that the `Clock` sets up a timer and updates the UI every second should be an implementation detail of the `Clock`.

Expand Down Expand Up @@ -89,20 +52,7 @@ You can convert a functional component like `Clock` to a class in five steps:

5. Delete the remaining empty function declaration.

```js
class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/zKRGpo?editors=0010)
[Run example.](source:examples/single-file-examples/src/state-and-lifecycle/state-and-lifecycle-3.js?editorsize=70&forcerefresh=1)

`Clock` is now defined as a class rather than a function.

Expand Down Expand Up @@ -171,30 +121,7 @@ We will later add the timer code back to the component itself.

The result looks like this:

```js{2-5,11,18}
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}

render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

ReactDOM.render(
<Clock />,
document.getElementById('root')
);
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/KgQpJd?editors=0010)
[Run example.](source:examples/single-file-examples/src/state-and-lifecycle/state-and-lifecycle-4.js{5,6,7,8,14,20}?editorsize=70)

Next, we'll make the `Clock` set up its own timer and update itself every second.

Expand Down Expand Up @@ -265,47 +192,7 @@ Finally, we will implement a method called `tick()` that the `Clock` component w

It will use `this.setState()` to schedule updates to the component local state:

```js{18-22}
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}

componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}

componentWillUnmount() {
clearInterval(this.timerID);
}

tick() {
this.setState({
date: new Date()
});
}

render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

ReactDOM.render(
<Clock />,
document.getElementById('root')
);
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/amqdNA?editors=0010)
[Run example.](source:examples/single-file-examples/src/state-and-lifecycle/state-and-lifecycle-5.js{18,19,20,21,22}?editorsize=70)

Now the clock ticks every second.

Expand Down Expand Up @@ -434,38 +321,15 @@ This also works for user-defined components:

The `FormattedDate` component would receive the `date` in its props and wouldn't know whether it came from the `Clock`'s state, from the `Clock`'s props, or was typed by hand:

```js
function FormattedDate(props) {
return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/zKRqNB?editors=0010)
[Run example.](source:examples/single-file-examples/src/state-and-lifecycle/state-and-lifecycle-6.js{4,5,6}?editorsize=70)

This is commonly called a "top-down" or "unidirectional" data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components "below" them in the tree.

If you imagine a component tree as a waterfall of props, each component's state is like an additional water source that joins it at an arbitrary point but also flows down.

To show that all components are truly isolated, we can create an `App` component that renders three `<Clock>`s:

```js{4-6}
function App() {
return (
<div>
<Clock />
<Clock />
<Clock />
</div>
);
}

ReactDOM.render(
<App />,
document.getElementById('root')
);
```

[Try it on CodePen.](http://codepen.io/gaearon/pen/vXdGmd?editors=0010)
[Run example.](source:examples/single-file-examples/src/state-and-lifecycle/state-and-lifecycle-7/index.js{9,10,11}?editorsize=70)

Each `Clock` sets up its own timer and updates independently.

Expand Down
28 changes: 1 addition & 27 deletions content/docs/uncontrolled-components.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,7 @@ To write an uncontrolled component, instead of writing an event handler for ever

For example, this code accepts a single name in an uncontrolled component:

```javascript{8,17}
class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(event) {
alert('A name was submitted: ' + this.input.value);
event.preventDefault();
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={(input) => this.input = input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
```

[Try it on CodePen.](https://codepen.io/gaearon/pen/WooRWa?editors=0010)
[Run the example.](source:examples/single-file-examples/src/uncontrolled-components.js{11,20}?editorsize=70)

Since an uncontrolled component keeps the source of truth in the DOM, it is sometimes easier to integrate React and non-React code when using uncontrolled components. It can also be slightly less code if you want to be quick and dirty. Otherwise, you should usually use controlled components.

Expand Down
21 changes: 21 additions & 0 deletions examples/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
!public

# dependencies
/node_modules

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
16 changes: 16 additions & 0 deletions examples/portals-1/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "portals-1",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-scripts": "1.0.14"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
Binary file added examples/portals-1/public/favicon.ico
Binary file not shown.
44 changes: 44 additions & 0 deletions examples/portals-1/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.

Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>

<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="app-root"></div>
<div id="modal-root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>

</html>
50 changes: 50 additions & 0 deletions examples/portals-1/src/App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React from 'react';

import Modal from './Modal';

// The Modal component is a normal React component, so we can
// render it wherever we like without needing to know that it's
// implemented with portals.
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {showModal: false};

this.handleShow = this.handleShow.bind(this);
this.handleHide = this.handleHide.bind(this);
}

handleShow() {
this.setState({showModal: true});
}

handleHide() {
this.setState({showModal: false});
}

render() {
// Show a Modal on click.
// (In a real app, don't forget to use ARIA attributes
// for accessibility!)
const modal = this.state.showModal ? (
<Modal>
<div className="modal">
<div>
With a portal, we can render content into a different part of the
DOM, as if it were any other React child.
</div>
This is being rendered inside the #modal-container div.
<button onClick={this.handleHide}>Hide modal</button>
</div>
</Modal>
) : null;

return (
<div className="app">
This div has overflow: hidden.
<button onClick={this.handleShow}>Show modal</button>
{modal}
</div>
);
}
}
Loading