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?
-
1Related non-React version: I've been told to do a “runnable” example with “Stack Snippets”, how do I do that?– T.J. CrowderNov 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. CrowderNov 7, 2017 at 12:54
-
Related feature request: One-click framework snippets– Nino FiliuMar 4, 2021 at 11:58
1 Answer
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:
Open the Stack Snippets editor by clicking the
toolbar button:
Pick your desired React version from the drop-down:
Note A: 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 https://cdnjs.com/); use the "UMD" versions. For instance, to use v17.0.2:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
Or to use v18.2.0:
<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>
Note B: The version of Babel used by Stack Snippets doesn't support
<>
and</>
for fragments, so use<React.Fragment>
and</React.Fragment>
instead.Note C: 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 / ES2015 checkbox; it doesn't say explicitly, but this is what enables JSX support, as the Babel configuration used includes JSX handling:
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 stateless functional component
const SFC = 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>
<SFC label="I'm the SFC 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.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
React v18.2.0:
// Example stateless functional component
const SFC = 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>
<SFC label="I'm the SFC 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.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>
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.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>
-
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? 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. 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. 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. 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. 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. 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". 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) 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) 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. Oct 27, 2020 at 18:33 -
@3limin4t0r cool, for the next time I'll give a try. Thanks for the tip :) Oct 27, 2020 at 20:02
-
@3limin4t0r - The real problem there is that SE hasn't updated the version of Babel standalone that it uses in years. Oct 28, 2020 at 7:48
-
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. 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 ;)) May 20, 2022 at 22:41