In the Stack Snippets editor, I can see a drop-down box for including a version of React, but how do I actually create a snippet using React with JSX in it?
-
2Related non-React version: I've been told to do a “runnable” example with “Stack Snippets”, how do I do that?– T.J. CrowderCommented Nov 7, 2017 at 12:41
-
1Related feature request: Add detailed help for Stack Snippets to the editor's “Code” section and the advanced help– T.J. CrowderCommented Nov 7, 2017 at 12:54
-
Related feature request: One-click framework snippets– Nino FiliuCommented Mar 4, 2021 at 11:58
2 Answers
Here's a step-by-step guide, first summary, then details with pictures. There are a couple of live demonstration snippets after the detailed instructions.
Summary:
Open the Stack Snippets editor by clicking the toolbar button.
Pick your desired React version from the drop-down on the left-hand side. (See the details below if you don't see the version you need in the list — note that as of March 2021 none of the built-in version options supports hooks, the details below [and a hooks example] say what to do.)
Tick the Use BabelJS / ES2015 checkbox; it doesn't say explicitly, but this is what enables JSX support, as the Babel configuration used includes JSX handling. (Note: Sadly, SE hasn't updated the version of Babel standalone that it uses in years, so that feature doesn't support shorthand fragments or
async
/await
. You can enable them if you need them (see the preceding link), it's just awkward.If you're not going to use the in-snippet console, this is a good time to un-tick that box.
If you have additional libraries, use the Add an external library button (or just
script
andlink
tags) to add them.Add your code in the JavaScript panel.
If your code is written in TypeScript, comment out the type annotations (and
type
andinterface
declarations) so it's valid JavaScript code.If your code needs ajax, you can easily simulate it by using static data and
setTimeout
.
If you use Hooks, you can either use them directly on
React
(React.useState
etc.) or to be more similar to how you probably use them in your real code, destructuring at the beginning (where you probably useimport
in your real code):const { useState } = React;
There's a Hooks example at the end of this answer.
At the end of your code, write a call to
ReactDOM.render
(up to v17.x) orReactDOM.createRoot
(v18.x+) telling it what to render and where: If you're using the in-snippet console, be sure to define the HTML for an element in the HTML pane and target that element with theReactDOM.render
call; if you aren't, you can render directly tobody
if you like. (Rendering tobody
doesn't work if you use the in-snippet console because it overwrites the console's element.)You're ready to run your React/JSX code! Click the Run button. Note that there may be a brief delay while scripts are loaded and the JSX is transpiled before your results appear in the results pane. As with any snippet, double-check that your snippet runs the way you mean it to (double-check the web console if not using the in-snippet console) and demonstrates what you want it to demonstrate (your specific issue, if asking a question; or the solution, if posting an answer).
Notes:
The version of Babel used by Stack Snippets doesn't support
<>
and</>
for fragments, so use<React.Fragment>
and</React.Fragment>
instead.The versions of React offered by the drop-down get out of date quickly, but you can easily edit to use an up-to-date version. For instance, if you select "React v16.6.3` from the drop-down, you can edit the script tags it includes to use v18.2.0 if you like.
Details:
(NOTE: Some of these screenshots are a bit out of date.)
Open the Stack Snippets editor by clicking the toolbar button:
Pick your desired React version from the drop-down:
If you need a later version than is offered in the drop-down, just pick the latest it has and then edit the version numbers in both
script
elements it inserts.Note: To use hooks, be sure to use v16.8 or later, and use
const { useState } = React;
and similar to get the hook functions; see the final example at the end of this answer.Tick the Use BabelJS (enables ES2015+, JSX) checkbox:
If you're not going to use the in-snippet console, this is a good time to un-tick that box.
If you have additional libraries, use the Add an external library button (or just
script
andlink
tags) to add them:(You can find just about everything hosted on a CDN somewhere, such as https://cdnjs.com/ [I have no affiliation with them].)
Add your code:
If our code needs ajax, you can easily simulate it with static data and
setTimeout
:Instead of:
fetch("/some/resource") .then(response => { if (!response.ok) { throw new Error("HTTP error " + response.status); } return response.json(); }) .then(data => { // ...use data here... }) .catch(/*...*/);
you'd do:
setTimeout(() => { // ...use data here... }, 800);
or if you need a promise:
return new Promise( resolve => setTimeout(resolve, 800, {/* ...data here... */}) );
If you use Hooks, you can either use them directly on
React
(React.useState
etc.) or to be more similar to how you probably use them in your real code, destructuring at the beginning (where you probably useimport
in your real code):const { useState } = React;
There's a Hooks example at the end of this answer.
At the end of your code, write a call to
ReactDOM.render
telling it what to render and where.As usual, you'll want to define an element in the HTML box:
<div id="root"></div>
...and then code the
ReactDOM
call like this, to render into that element:// v15.x, v16.x, v17.x ReactDOM.render( <Thingy title="I'm the thingy" />, document.getElementById("root") );
or
// v18.x+ ReactDOM.createRoot( document.getElementById("root") ).render( <Thingy title="I'm the thingy" /> );
Example (there's a live copy below as well):
You're ready to run your React/JSX code! Click the Run button. Make sure that the snippet runs and demonstrates the problem you're trying to show.
Note that there may be a brief delay while scripts are loaded and the JSX is transpiled before your results appear in the results pane. As with any snippet, double-check that your snippet runs the way you mean it to (double-check the web console if not using the in-snippet console) and demonstrates what you want it to demonstrate (your specific issue, if asking a question; or the solution, if posting an answer).
Live copy of rendering into an element and using the snippet console
React v17.0.2 (see Step 2, Note A of Details above for how we got v17.0.2 when the latest in the list is v16.6.3):
// Example function component
const ExampleFC = (props) => (
<div>{props.label}</div>
);
// Example class component
class Thingy extends React.Component {
render() {
const { title } = this.props;
console.log("rendered");
return (
<div>
<div>{title}</div>
<ExampleFC label="I'm the function component inside the Thingy" />
</div>
);
}
}
// Render it
ReactDOM.render(
<Thingy title="I'm the thingy" />,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
React v18.2.0:
// Example stateless function component
const ExampleFC = props => (
<div>{props.label}</div>
);
// Example class component
class Thingy extends React.Component {
render() {
const { title } = this.props;
console.log("rendered");
return (
<div>
<div>{title}</div>
<ExampleFC label="I'm the function component inside the Thingy" />
</div>
);
}
}
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<Thingy title="I'm the thingy" />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
Live example using Hooks
Note: See Step 2, Note A in the Details above. To use hooks, you have to provide the React scripts explicitly, not via the drop-down, as the drop-down is outdated.
// Get a hook function
const { useState} = React;
const Example = ({ title }) => {
const [count, setCount] = useState(0);
return (
<div>
<p>{title}</p>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
};
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<Example title="Example using Hooks:" />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
Live example using StrictMode
Note: See Step 2, Note A in the Details above. To use hooks, you have to provide the React scripts explicitly, not via the drop-down, as the drop-down is outdated.
// Get a hook function
const { useState, StrictMode } = React;
const Example = ({ title }) => {
const [count, setCount] = useState(0);
console.log(`Example rendered with count = ${count}`);
return (
<div>
<p>{title}</p>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
};
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<StrictMode>
<Example title="Example using StrictMode (notice that Example renders twice on mount and some other times)" />
</StrictMode>
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
-
1What if I'm adding an external react library and I want to use it? let's say react-bootstrap or any other. Is that possible? Commented Dec 2, 2019 at 3:35
-
@AlterLagos - In most cases, yes. Use the "Add an external library" button or add the necessary
script
and/orlink
tags in the HTML pane. Commented Dec 2, 2019 at 7:01 -
1Sorry, I didn't explain at all my question. I'm adding
react-bootstrap
from a CDN in ascript
tag, then I don't find a way to use it in my snippet code. I tried usingimport {Button} from 'react-bootstrap';
but is throwingUncaught ReferenceError: require is not defined
. I don't find a way to assign it to aconst
either, as it seemsimport
isn't enabled by default. Commented Dec 2, 2019 at 21:26 -
1@AlterLagos - You need a build of it that doesn't use
require
orimport
/export
, such as the "UMD" builds of the React scripts above. Commented Dec 3, 2019 at 7:00 -
1@Sharcoux - That is noted, in the answer above (under Details, Step 2). :-) I've edited to add a reminder about that just above the Hooks example at the end. Commented Mar 9, 2020 at 11:24
-
As far as I can tell, currently (2020-03-29) react hooks are not available, because the latest reactjs allowed in the dropdown is 16.6.3, and hooks need 16.8. Commented Mar 29, 2020 at 21:45
-
@KlasMellbourn - Step 2 explains what to do about that: "At the moment, the list goes up through v16.6.3. To use hooks and such, you'll need later versions. You can grab the latest from a CDN (like cdnjs.com); use the "UMD" versions. For instance, to use v16.8.4:" followed by script tag examples for 16.8.4 (out of date now). There's also the "Live example using Hooks". Commented Mar 30, 2020 at 7:03
-
1@AlterLagos You have to use the CDN variant. Most of the times these are provided in the "getting started" or "installation" section of the library documentation. If you can't find them there you can always try cdnjs.com or unpkg.com.
react-bootstrap
does offer its own documentation. Here the documentation also says that the components are available via theReactBootstrap
global. So you can doconst { Button } = ReactBootstrap;
(1/2) Commented Oct 27, 2020 at 18:09 -
If the global is not documented I often use use something like
console.log(Object.keys(window).filter(name => name.match(/bootstrap/i)))
to find all globals that have "bootstrap" (case insensitive) in the name. Here you replace/bootstrap/i
with something that is most likely going to match. If you cannot find it using this method you can always useconsole.log(Object.keys(window).sort())
to display all globals in alphabetical order. However this list will be a lot longer. (2/2) Commented Oct 27, 2020 at 18:17 -
Note that by checking Use BabelJS / ES2015 you do enable JSX support, however ES2015 does not support
async
/await
, so you have to work with promises. Commented Oct 27, 2020 at 18:33 -
3
-
2@TJ - Yeah. And the libs list is out of date. And the Babel version is so old that it doesn't understand
async
functions (!). And. And. And. :-| But by all means, let's spend more time finding new ways to advertise Teams to SO contributors. Commented Apr 29, 2021 at 13:38 -
1@Sean Done. Let us know if there's any that don't make sense (or feel free to edit them yourself ;)) Commented May 20, 2022 at 22:41
-
1@T.J.Crowder I added a response below for getting Babel 7 support. Commented Oct 4, 2023 at 16:10
-
1I must have been messing up somewhere. Thanks. I just copied your code and it started workin. Commented May 18 at 13:58
Currently, Stack Snippets use Babel version 6.10.3 (circa June 18, 2016).
The following ES7+ features are unsupported:
- Async functions (
async
/await
) - Optional chaining (
?.
) - Nullish-coalescing (
??
) and assignment (??=
) - Shorthand for
<React.Fragment>
(<></>
)
As a follow-up to T.J. Crowder's awesome response, I have crafted a template using React 18 and Babel 7.
My inspiration came from the following post:
Update the version of Babel Standalone (and others) used by Stack Snippets
Here is the snippet. Please note that I placed the JSX code inside the HTML viewport of the snippet editor. This is required so that Babel can process the JSX correctly. I added examples of callbacks, effects, states, and memoization.
.App button:last-child {
margin-left: 0.5rem;
}
<div id="root"></div>
<script type="text/babel" data-presets="es2017,react">
/* BEGIN ES2017 (ES8) React code... */
const { useCallback, useEffect, useMemo, useState } = React;
const App = ({ initialCount = 0, step = 1, title = 'APP_TITLE' }) => {
const [name, setName] = useState('...');
const [count, setCount] = useState(initialCount ?? 0);
useEffect(() => {
(async () => {
const response = await fetch('https://swapi.dev/api/people/1');
const person = await response.json();
setName(person?.name);
})();
}, []);
const updateCount = useCallback((event) => {
setCount((currentCount) => currentCount + step);
}, []);
const resetCount = useCallback(() => {
setCount(initialCount);
}, [initialCount]);
const clickDisabled = useMemo(() => count <= 0, [count]);
return (
<div className="App">
<h1>{title}</h1>
<p>{name}, you have {count} tries left.</p>
<>
<button disabled={clickDisabled} onClick={updateCount}>Click me</button>
<button onClick={resetCount}>Reset</button>
</>
</div>
);
};
// Render it
ReactDOM
.createRoot(document.getElementById('root'))
.render(<App initialCount={10} step={-1} title="Example using Hooks" />);
/* END ES2017 (ES8) React code... */
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.1/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
-
1Great stuff! Now if only SE Inc would bother to spend the brief amount of engineering time it would take to fix Stack Snippets. Commented Oct 5, 2023 at 6:18