Files
30-seconds-of-code/snippet_data/snippets.json
30secondsofcode 36a7307d87 Travis build: 149
2019-11-18 15:47:46 +00:00

965 lines
80 KiB
JSON

{
"data": [
{
"id": "Accordion",
"title": "Accordion",
"type": "snippet",
"attributes": {
"fileName": "Accordion.md",
"text": "Renders an accordion menu with multiple collapsible content components.\n\n- Define an `AccordionItem` component, pass it to the `Accordion` and remove unnecessary nodes expect for `AccordionItem` by identifying the function's name in `props.children`.\n- Each `AccordionItem` component renders a `<button>` that is used to update the `Accordion` via the `props.handleClick` callback and the content of the component, passed down via `props.children`, while its appearance is determined by `props.isCollapsed` and based on `style`.\n- In the `Accordion` component, use the `React.useState()` hook to initialize the value of the `bindIndex` state variable to `props.defaultIndex`.\n- Use `Array.prototype.map` on the collected nodes to render the individual collapsiple elements.\n- Define `changeItem`, which will be executed when clicking an `AccordionItem`'s `<button>`.\n `changeItem` executes the passed callback, `onItemClick` and updates `bindIndex` based on the clicked element.\n\n",
"codeBlocks": {
"style": "",
"code": "function AccordionItem(props) {\n const style = {\n collapsed: {\n display: 'none'\n },\n expanded: {\n display: 'block'\n },\n buttonStyle: {\n display: 'block',\n width: '100%'\n }\n };\n\n return (\n <div>\n <button style={style.buttonStyle} onClick={() => props.handleClick()}>\n {props.label}\n </button>\n <div\n className=\"collapse-content\"\n style={props.isCollapsed ? style.collapsed : style.expanded}\n aria-expanded={props.isCollapsed}\n >\n {props.children}\n </div>\n </div>\n );\n}\n\nfunction Accordion(props) {\n const [bindIndex, setBindIndex] = React.useState(props.defaultIndex);\n\n const changeItem = itemIndex => {\n if (typeof props.onItemClick === 'function') props.onItemClick(itemIndex);\n if (itemIndex !== bindIndex) setBindIndex(itemIndex);\n };\n const items = props.children.filter(item => item.type.name === 'AccordionItem');\n\n return (\n <div className=\"wrapper\">\n {items.map(({ props }) => (\n <AccordionItem\n isCollapsed={bindIndex !== props.index}\n label={props.label}\n handleClick={() => changeItem(props.index)}\n children={props.children}\n />\n ))}\n </div>\n );\n}",
"example": "ReactDOM.render(\n <Accordion defaultIndex=\"1\" onItemClick={console.log}>\n <AccordionItem label=\"A\" index=\"1\">\n Lorem ipsum\n </AccordionItem>\n <AccordionItem label=\"B\" index=\"2\">\n Dolor sit amet\n </AccordionItem>\n </Accordion>,\n document.getElementById('root')\n);"
},
"tags": [
"visual",
"children",
"state",
"advanced"
]
},
"meta": {
"hash": "b83c2546a50390dcda27afa3bd654fc6b70474e624cdd80ef6862f7d14c2c7c6",
"firstSeen": "1566386637",
"lastUpdated": "1568614478",
"updateCount": 3
}
},
{
"id": "Alert",
"title": "Alert",
"type": "snippet",
"attributes": {
"fileName": "Alert.md",
"text": "Creates an alert component with `type` prop.\n\n- Define appropriate CSS styles and animations for the component's elements.\n- Use the `React.setState()` hook to create the `isShown` and `isLeaving` state variables and set their values to `false`.\n- Define `timeoutId` to keep the timer instance for clearing on component unmount.\n- Use the `React.setEffect()` hook to update the value of `isShown` to `true` and clear interval by using `timeoutId` when component is unmounted.\n- Define `closeNotification` function to set the component is removed from DOM by displaying fading out animation and set `isShown` to `false` via `setTimeout()`. \n- Define the component, which renders the alert component with user defined `message` and a close button to remove the component from DOM.\n\n",
"codeBlocks": {
"style": "@keyframes leave {\n 0% { opacity: 1 }\n 100% { opacity: 0 }\n}\n\n.alert {\n padding: 0.75rem 0.5rem;\n margin-bottom: 0.5rem;\n text-align: left;\n padding-right: 40px;\n border-radius: 4px;\n font-size: 16px;\n position: relative;\n}\n\n.alert.warning{\n color: #856404;\n background-color: #fff3cd;\n border-color: #ffeeba;\n}\n\n.alert.error{\n color: #721c24;\n background-color: #f8d7da;\n border-color: #f5c6cb;\n}\n\n.alert.leaving{\n animation: leave 0.5s forwards;\n}\n\n.alert .close {\n position: absolute;\n top: 0;\n right: 0;\n padding: 0 0.75rem;\n color: #333;\n border: 0;\n height: 100%;\n cursor: pointer;\n background: none;\n font-weight: 600;\n font-size: 16px;\n}\n\n.alert .close:after{\n content: 'x';\n}",
"code": "function Notification(props) {\n const [isShown, setIsShown] = React.useState(false);\n const [isLeaving, setIsLeaving] = React.useState(false);\n\n let timeoutId = null;\n\n React.useEffect(() => {\n setIsShown(true);\n return () => {\n clearTimeout(timeoutId);\n }\n }, [props.isShown, props.timeout, timeoutId]);\n\n const closeNotification = () => {\n setIsLeaving(true);\n timeoutId = setTimeout(() => {\n setIsLeaving(false);\n setIsShown(false);\n }, 250)\n }\n\n return isShown && (\n <div className={`alert ${props.type}${isLeaving ? ' leaving' : ''}`} role=\"alert\">\n <button className=\"close\" onClick={closeNotification} />\n {props.message}\n </div>\n )\n}",
"example": "ReactDOM.render(<Notification type=\"info\" message=\"This is info\" />, document.getElementById('root'));"
},
"tags": [
"visual",
"beginner",
"state",
"effect"
]
},
"meta": {
"hash": "6a9a1148d22c55f24865ce2672a84222409769910a5e472ab80e353c61914ab8",
"firstSeen": "1568715570",
"lastUpdated": "1568951771",
"updateCount": 4
}
},
{
"id": "AutoLink",
"title": "AutoLink",
"type": "snippet",
"attributes": {
"fileName": "AutoLink.md",
"text": "Renders a string as plaintext, with URLs converted to appropriate `<a>` elements.\n\n- Use `String.prototype.split()` and `String.prototype.match()` with a regular expression to find URLs in a string.\n- Return a `<React.Fragment>` with matched URLs rendered as `<a>` elements, dealing with missing protocol prefixes if necessary, and the rest of the string rendered as plaintext.\n\n",
"codeBlocks": {
"style": "",
"code": "function AutoLink({ text }) {\n const delimiter = /((?:https?:\\/\\/)?(?:(?:[a-z0-9]?(?:[a-z0-9\\-]{1,61}[a-z0-9])?\\.[^\\.|\\s])+[a-z\\.]*[a-z]+|(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})(?::\\d{1,5})*[a-z0-9.,_\\/~#&=;%+?\\-\\\\(\\\\)]*)/gi;\n\n return (\n <React.Fragment>\n {text.split(delimiter).map(word => {\n let match = word.match(delimiter);\n if (match) {\n let url = match[0];\n return <a href={url.startsWith('http') ? url : `http://${url}`}>{url}</a>;\n }\n return word;\n })}\n </React.Fragment>\n );\n}",
"example": "ReactDOM.render(\n <AutoLink text=\"foo bar baz http://example.org bar\" />,\n document.getElementById('root')\n);"
},
"tags": [
"visual",
"string",
"fragment",
"regexp",
"advanced"
]
},
"meta": {
"hash": "922aeac82b3a5a51e05d84e1795a84eab79106d8052edb857a7cd7db6bf41917",
"firstSeen": "1566386637",
"lastUpdated": "1566387134",
"updateCount": 4
}
},
{
"id": "Carousel",
"title": "Carousel",
"type": "snippet",
"attributes": {
"fileName": "Carousel.md",
"text": "Renders a carousel component.\n\n- Use the `React.setState()` hook to create the `active` state variable and give it a value of `0` (index of the first item).\n- Use an object, `style`, to hold the styles for the individual components.\n- Use the `React.useEffect()` hook to update the value of `active` to the index of the next item, using `setTimeout`.\n- Destructure `props`, compute if visibility style should be set to `visible` or not for each carousel item while mapping over and applying the combined style to the carousel item component accordingly.\n- Render the carousel items using `React.cloneElement()` and pass down rest `props` along with the computed styles.\n\n",
"codeBlocks": {
"style": "",
"code": "function Carousel(props) {\n const [active, setActive] = React.useState(0);\n let scrollInterval = null;\n const style = {\n carousel: {\n position: 'relative'\n },\n carouselItem: {\n position: 'absolute',\n visibility: 'hidden'\n },\n visible: {\n visibility: 'visible'\n }\n };\n React.useEffect(() => {\n scrollInterval = setTimeout(() => {\n const { carouselItems } = props;\n setActive((active + 1) % carouselItems.length);\n }, 2000);\n return () => clearTimeout(scrollInterval);\n });\n const { carouselItems, ...rest } = props;\n return (\n <div style={style.carousel}>\n {carouselItems.map((item, index) => {\n const activeStyle = active === index ? style.visible : {};\n return React.cloneElement(item, {\n ...rest,\n style: {\n ...style.carouselItem,\n ...activeStyle\n }\n });\n })}\n </div>\n );\n}",
"example": "ReactDOM.render(\n <Carousel\n carouselItems={[\n <div>carousel item 1</div>,\n <div>carousel item 2</div>,\n <div>carousel item 3</div>\n ]}\n />,\n document.getElementById('root')\n);"
},
"tags": [
"visual",
"children",
"state",
"effect",
"intermediate"
]
},
"meta": {
"hash": "4e224ce57a85a9061c065603496ae2a80db43d2ab7908d1c08c7dcbe5779a2d6",
"firstSeen": "1566386637",
"lastUpdated": "1568839108",
"updateCount": 3
}
},
{
"id": "Collapse",
"title": "Collapse",
"type": "snippet",
"attributes": {
"fileName": "Collapse.md",
"text": "Renders a component with collapsible content.\n\n- Use the `React.setState()` hook to create the `isCollapsed` state variable with an initial value of `props.collapsed`.\n- Use an object, `style`, to hold the styles for individual components and their states.\n- Use a `<div>` to wrap both the `<button>` that alters the component's `isCollapsed` state and the content of the component, passed down via `props.children`.\n- Determine the appearance of the content, based on `isCollapsed` and apply the appropriate CSS rules from the `style` object.\n- Finally, update the value of the `aria-expanded` attribute based on `isCollapsed` to make the component accessible.\n\n",
"codeBlocks": {
"style": "",
"code": "function Collapse(props) {\n const [isCollapsed, setIsCollapsed] = React.useState(props.collapsed);\n\n const style = {\n collapsed: {\n display: 'none'\n },\n expanded: {\n display: 'block'\n },\n buttonStyle: {\n display: 'block',\n width: '100%'\n }\n };\n\n return (\n <div>\n <button style={style.buttonStyle} onClick={() => setIsCollapsed(!isCollapsed)}>\n {isCollapsed ? 'Show' : 'Hide'} content\n </button>\n <div\n className=\"collapse-content\"\n style={isCollapsed ? style.collapsed : style.expanded}\n aria-expanded={isCollapsed}\n >\n {props.children}\n </div>\n </div>\n );\n}",
"example": "ReactDOM.render(\n <Collapse>\n <h1>This is a collapse</h1>\n <p>Hello world!</p>\n </Collapse>,\n document.getElementById('root')\n);"
},
"tags": [
"visual",
"children",
"state",
"intermediate"
]
},
"meta": {
"hash": "d6efbb46da30a701cc691ad94b860fb6f0b34459e88caa8d744411734503af8f",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "ControlledInput",
"title": "ControlledInput",
"type": "snippet",
"attributes": {
"fileName": "ControlledInput.md",
"text": "Renders an `<input>` element with internal state, that uses a callback function to pass its value to the parent component.\n\n- Use object destructuring to set defaults for certain attributes of the `<input>` element.\n- Use the `React.setState()` hook to create the `value` state variable and give it a value of equal to the `defaultValue` prop.\n- Use the `React.useEffect()` hook with a second parameter set to the `value` state variable to call the `callback` function every time `value` is updated.\n- Render an `<input>` element with the appropriate attributes and use the the `onChange` event to upda the `value` state variable.\n\n",
"codeBlocks": {
"style": "",
"code": "function ControlledInput({\n callback,\n type = 'text',\n disabled = false,\n readOnly = false,\n defaultValue,\n placeholder = ''\n}) {\n const [value, setValue] = React.useState(defaultValue);\n\n React.useEffect(() => {\n callback(value);\n }, [value]);\n\n return (\n <input\n defaultValue={defaultValue}\n type={type}\n disabled={disabled}\n readOnly={readOnly}\n placeholder={placeholder}\n onChange={({ target: { value } }) => setValue(value)}\n />\n );\n}",
"example": "ReactDOM.render(\n <ControlledInput\n type=\"text\"\n placeholder=\"Insert some text here...\"\n callback={val => console.log(val)}\n />,\n document.getElementById('root')\n);"
},
"tags": [
"input",
"state",
"effect",
"intermediate"
]
},
"meta": {
"hash": "25ac64175964945e36212d776ef5192d54628e1d08561489a022765c45368692",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "CountDown",
"title": "CountDown",
"type": "snippet",
"attributes": {
"fileName": "CountDown.md",
"text": "Renders a countdown timer that prints a message when it reaches zero.\n\n- Use object destructuring to set defaults for the `hours`, `minutes` and `seconds` props.\n- Use the `React.useState()` hook to create the `time`, `paused` and `over` state variables and set their values to the values of the passed props, `false` and `false` respectively.\n- Create a method `tick`, that updates the value of `time` based on the current value (i.e. decreasing the time by one second).\n- If `paused` or `over` is `true`, `tick` will return immediately.\n- Create a method `reset`, that resets all state variables to their initial states.\n- Use the the `React.useEffect()` hook to call the `tick` method every second via the use of `setInterval()` and use `clearInterval()` to cleanup when the component is unmounted.\n- Use a `<div>` to wrap a `<p>` element with the textual representation of the components `time` state variable, as well as two `<button>` elements that will pause/unpause and restart the timer respectively.\n- If `over` is `true`, the timer will display a message instead of the value of `time`.\n\n",
"codeBlocks": {
"style": "",
"code": "function CountDown({ hours = 0, minutes = 0, seconds = 0 }) {\n const [paused, setPaused] = React.useState(false);\n const [over, setOver] = React.useState(false);\n const [time, setTime] = React.useState({\n hours: parseInt(hours),\n minutes: parseInt(minutes),\n seconds: parseInt(seconds)\n });\n\n const tick = () => {\n if (paused || over) return;\n if (time.hours == 0 && time.minutes == 0 && time.seconds == 0) setOver(true);\n else if (time.minutes == 0 && time.seconds == 0)\n setTime({\n hours: time.hours - 1,\n minutes: 59,\n seconds: 59\n });\n else if (time.seconds == 0)\n setTime({\n hours: time.hours,\n minutes: time.minutes - 1,\n seconds: 59\n });\n else\n setTime({\n hours: time.hours,\n minutes: time.minutes,\n seconds: time.seconds - 1\n });\n };\n\n const reset = () => {\n setTime({\n hours: parseInt(hours),\n minutes: parseInt(minutes),\n seconds: parseInt(seconds)\n });\n setPaused(false);\n setOver(false);\n };\n\n React.useEffect(() => {\n let timerID = setInterval(() => tick(), 1000);\n return () => clearInterval(timerID);\n });\n\n return (\n <div>\n <p>{`${time.hours.toString().padStart(2, '0')}:${time.minutes\n .toString()\n .padStart(2, '0')}:${time.seconds.toString().padStart(2, '0')}`}</p>\n <div>{over ? \"Time's up!\" : ''}</div>\n <button onClick={() => setPaused(!paused)}>{paused ? 'Resume' : 'Pause'}</button>\n <button onClick={() => reset()}>Restart</button>\n </div>\n );\n}",
"example": "ReactDOM.render(<CountDown hours=\"1\" minutes=\"45\" />, document.getElementById('root'));"
},
"tags": [
"visual",
"state",
"advanced"
]
},
"meta": {
"hash": "fb5aeef0abd03d44daaff0bd027c7633fe4b079f07c13f2cb3166a56363453ef",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "DataList",
"title": "DataList",
"type": "snippet",
"attributes": {
"fileName": "DataList.md",
"text": "Renders a list of elements from an array of primitives.\n\n- Use the value of the `isOrdered` prop to conditionally render a `<ol>` or `<ul>` list.\n- Use `Array.prototype.map` to render every item in `data` as a `<li>` element, give it a `key` produced from the concatenation of the its index and value.\n- Omit the `isOrdered` prop to render a `<ul>` list by default.\n\n",
"codeBlocks": {
"style": "",
"code": "function DataList({ isOrdered, data }) {\n const list = data.map((val, i) => <li key={`${i}_${val}`}>{val}</li>);\n return isOrdered ? <ol>{list}</ol> : <ul>{list}</ul>;\n}",
"example": "const names = ['John', 'Paul', 'Mary'];\nReactDOM.render(<DataList data={names} />, document.getElementById('root'));\nReactDOM.render(<DataList data={names} isOrdered />, document.getElementById('root'));"
},
"tags": [
"array",
"beginner"
]
},
"meta": {
"hash": "9c5d1b4aee999583a6f01ef38b0060a2eedcb27e215246e0cf31a5e43e53c0f5",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "DataTable",
"title": "DataTable",
"type": "snippet",
"attributes": {
"fileName": "DataTable.md",
"text": "Renders a table with rows dynamically created from an array of primitives.\n\n- Render a `<table>` element with two columns (`ID` and `Value`).\n- Use `Array.prototype.map` to render every item in `data` as a `<tr>` element, consisting of its index and value, give it a `key` produced from the concatenation of the two.\n\n",
"codeBlocks": {
"style": "",
"code": "function DataTable({ data }) {\n return (\n <table>\n <thead>\n <tr>\n <th>ID</th>\n <th>Value</th>\n </tr>\n </thead>\n <tbody>\n {data.map((val, i) => (\n <tr key={`${i}_${val}`}>\n <td>{i}</td>\n <td>{val}</td>\n </tr>\n ))}\n </tbody>\n </table>\n );\n}",
"example": "const people = ['John', 'Jesse'];\nReactDOM.render(<DataTable data={people} />, document.getElementById('root'));"
},
"tags": [
"array",
"beginner"
]
},
"meta": {
"hash": "1ad27574cfe29f8cce5410e7dd243d66edeea801037e3cd0ed1d24ecdbd5526e",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "FileDrop",
"title": "FileDrop",
"type": "snippet",
"attributes": {
"fileName": "FileDrop.md",
"text": "Renders a file drag and drop component for a single file.\n\n- Create a ref called `dropRef` for this component.\n- Use the `React.useState()` hook to create the `drag` and `filename` variables, initialized to `false` and `''` respectively.\n The variables `dragCounter` and `drag` are used to determine if a file is being dragged, while `filename` is used to store the dropped file's name.\n- Create the `handleDrag`, `handleDragIn`, `handleDragOut` and `handleDrop` methods to handle drag and drop functionality, bind them to the component's context.\n- Each of the methods will handle a specific event, the listeners for which are created and removed in the `React.useEffect()` hook and its attached `cleanup()` method.\n- `handleDrag` prevents the browser from opening the dragged file, `handleDragIn` and `handleDragOut` handle the dragged file entering and exiting the component, while `handleDrop` handles the file being dropped and passes it to `props.handleDrop`.\n- Return an appropriately styled `<div>` and use `drag` and `filename` to determine its contents and style.\n- Finally, bind the `ref` of the created `<div>` to `dropRef`.\n\n",
"codeBlocks": {
"style": ".filedrop {\n min-height: 120px;\n border: 3px solid #d3d3d3;\n text-align: center;\n font-size: 24px;\n padding: 32px;\n border-radius: 4px;\n}\n\n.filedrop.drag {\n border: 3px dashed #1e90ff;\n}\n\n.filedrop.ready {\n border: 3px solid #32cd32;\n}",
"code": "function FileDrop(props) {\n const [drag, setDrag] = React.useState(false);\n const [filename, setFilename] = React.useState('');\n let dropRef = React.createRef();\n let dragCounter = 0;\n\n const handleDrag = e => {\n e.preventDefault();\n e.stopPropagation();\n };\n\n const handleDragIn = e => {\n e.preventDefault();\n e.stopPropagation();\n dragCounter++;\n if (e.dataTransfer.items && e.dataTransfer.items.length > 0) setDrag(true);\n };\n\n const handleDragOut = e => {\n e.preventDefault();\n e.stopPropagation();\n dragCounter--;\n if (dragCounter === 0) setDrag(false);\n };\n\n const handleDrop = e => {\n e.preventDefault();\n e.stopPropagation();\n setDrag(false);\n if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {\n props.handleDrop(e.dataTransfer.files[0]);\n setFilename(e.dataTransfer.files[0].name);\n e.dataTransfer.clearData();\n dragCounter = 0;\n }\n };\n\n React.useEffect(() => {\n let div = dropRef.current;\n div.addEventListener('dragenter', handleDragIn);\n div.addEventListener('dragleave', handleDragOut);\n div.addEventListener('dragover', handleDrag);\n div.addEventListener('drop', handleDrop);\n return function cleanup() {\n div.removeEventListener('dragenter', handleDragIn);\n div.removeEventListener('dragleave', handleDragOut);\n div.removeEventListener('dragover', handleDrag);\n div.removeEventListener('drop', handleDrop);\n };\n });\n\n return (\n <div\n ref={dropRef}\n className={drag ? 'filedrop drag' : filename ? 'filedrop ready' : 'filedrop'}\n >\n {filename && !drag ? <div>{filename}</div> : <div>Drop files here!</div>}\n </div>\n );\n}",
"example": "ReactDOM.render(<FileDrop handleDrop={console.log} />, document.getElementById('root'));"
},
"tags": [
"visual",
"input",
"state",
"effect",
"event",
"intermediate"
]
},
"meta": {
"hash": "083b5e03f65112796bebc1fb5b8db99c7cd7ff16a11cca192ad18ea5db5c7e30",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "LimitedTextarea",
"title": "LimitedTextarea",
"type": "snippet",
"attributes": {
"fileName": "LimitedTextarea.md",
"text": "Renders a textarea component with a character limit.\n\n- Use the `React.useState()` hook to create the `content` state variable and set its value to `value`.\n Create a method `setFormattedContent`, which trims the content of the input if it's longer than `limit`.\n- Use the `React.useEffect()` hook to call the `setFormattedContent` method on the value of the `content` state variable.\n- Use a`<div>` to wrap both the`<textarea>` and the `<p>` element that displays the character count and bind the `onChange` event of the `<textarea>` to call `setFormattedContent` with the value of `event.target.value`.\n\n",
"codeBlocks": {
"style": "",
"code": "function LimitedTextarea({ rows, cols, value, limit }) {\n const [content, setContent] = React.useState(value);\n\n const setFormattedContent = text => {\n text.length > limit ? setContent(text.slice(0, limit)) : setContent(text);\n };\n\n React.useEffect(() => {\n setFormattedContent(content);\n }, []);\n\n return (\n <div>\n <textarea\n rows={rows}\n cols={cols}\n onChange={event => setFormattedContent(event.target.value)}\n value={content}\n />\n <p>\n {content.length}/{limit}\n </p>\n </div>\n );\n}",
"example": "ReactDOM.render(<LimitedTextarea limit={32} value=\"Hello!\" />, document.getElementById('root'));"
},
"tags": [
"input",
"state",
"effect",
"event",
"beginner"
]
},
"meta": {
"hash": "b4b4fbf568331843e4734aa58831dd0c94afc5aeb7d987c8afcf9e9b24f0aeea",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "LimitedWordTextarea",
"title": "LimitedWordTextarea",
"type": "snippet",
"attributes": {
"fileName": "LimitedWordTextarea.md",
"text": "Renders a textarea component with a word limit.\n\n- Use the `React.useState()` hook to create the `content` and `wordCount` state variables and set their values to `value` and `0` respectively.\n- Create a method `setFormattedContent`, which uses `String.prototype.split(' ')` to turn the input into an array of words and check if the result of applying `Array.prototype.filter(Boolean)` has a `length` longer than `limit`.\n- If the afforementioned `length` exceeds the `limit`, trim the input, otherwise return the raw input, updating `content` and `wordCount` accordingly in both cases.\n- Use the `React.useEffect()` hook to call the `setFormattedContent` method on the value of the `content` state variable.\n- Use a`<div>` to wrap both the`<textarea>` and the `<p>` element that displays the character count and bind the `onChange` event of the `<textarea>` to call `setFormattedContent` with the value of `event.target.value`.\n\n",
"codeBlocks": {
"style": "",
"code": "function LimitedWordTextarea({ rows, cols, value, limit }) {\n const [content, setContent] = React.useState(value);\n const [wordCount, setWordCount] = React.useState(0);\n\n const setFormattedContent = text => {\n let words = text.split(' ');\n if (words.filter(Boolean).length > limit) {\n setContent(\n text\n .split(' ')\n .slice(0, limit)\n .join(' ')\n );\n setWordCount(limit);\n } else {\n setContent(text);\n setWordCount(words.filter(Boolean).length);\n }\n };\n\n React.useEffect(() => {\n setFormattedContent(content);\n }, []);\n\n return (\n <div>\n <textarea\n rows={rows}\n cols={cols}\n onChange={event => setFormattedContent(event.target.value)}\n value={content}\n />\n <p>\n {wordCount}/{limit}\n </p>\n </div>\n );\n}",
"example": "ReactDOM.render(\n <LimitedWordTextarea limit={5} value=\"Hello there!\" />,\n document.getElementById('root')\n);"
},
"tags": [
"input",
"state",
"effect",
"event",
"beginner"
]
},
"meta": {
"hash": "ac22f33a0084fb444ce9e3cd7aebec507d6d785d1bc6e0a9cc5656f5ee0cb92f",
"firstSeen": "1566386637",
"lastUpdated": "1569328773",
"updateCount": 3
}
},
{
"id": "Loader",
"title": "Loader",
"type": "snippet",
"attributes": {
"fileName": "Loader.md",
"text": "Creates a spinning loader component.\n\n- Define appropriate CSS styles and animations for the component's elements.\n- Define the component, which returns a simple SVG, whose size is determined by the `size` prop.\n\n",
"codeBlocks": {
"style": ".loader {\n animation: rotate 2s linear infinite;\n}\n\n@keyframes rotate {\n 100% {\n transform: rotate(360deg);\n }\n}\n\n.loader circle {\n animation: dash 1.5s ease-in-out infinite;\n}\n\n@keyframes dash {\n 0% {\n stroke-dasharray: 1, 150;\n stroke-dashoffset: 0;\n }\n 50% {\n stroke-dasharray: 90, 150;\n stroke-dashoffset: -35;\n }\n 100% {\n stroke-dasharray: 90, 150;\n stroke-dashoffset: -124;\n }\n}",
"code": "function Loader({ size }) {\n return (\n <svg\n className=\"loader\"\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n </svg>\n );\n}",
"example": "ReactDOM.render(<Loader size={24} />, document.getElementById('root'));"
},
"tags": [
"visual",
"beginner"
]
},
"meta": {
"hash": "c64381d332ae68b271f644add7cdc15c6027c7ee6945c3d1f507bd7eeebf253d",
"firstSeen": "1568228352",
"lastUpdated": "1568228352",
"updateCount": 2
}
},
{
"id": "Mailto",
"title": "Mailto",
"type": "snippet",
"attributes": {
"fileName": "Mailto.md",
"text": "Renders a link formatted to send an email.\n\n- Destructure the component's props, use `email`, `subject` and `body` to create a `<a>` element with an appropriate `href` attribute.\n- Render the link with `props.children` as its content.\n\n",
"codeBlocks": {
"style": "",
"code": "function Mailto({ email, subject, body, ...props }) {\n return (\n <a href={`mailto:${email}?subject=${encodeURIComponent(subject) || ''}&body=${encodeURIComponent(body) || ''}`}>{props.children}</a>\n );\n}",
"example": "ReactDOM.render(\n <Mailto email=\"foo@bar.baz\" subject=\"Hello & Welcome\" body=\"Hello world!\">\n Mail me!\n </Mailto>,\n document.getElementById('root')\n);"
},
"tags": [
"visual",
"beginner"
]
},
"meta": {
"hash": "f4186bc638098d4d510a26dac586a5196ffb2e0d41e3325a0e53756f26896c4c",
"firstSeen": "1566386637",
"lastUpdated": "1567859238",
"updateCount": 4
}
},
{
"id": "MappedTable",
"title": "MappedTable",
"type": "snippet",
"attributes": {
"fileName": "MappedTable.md",
"text": "Renders a table with rows dynamically created from an array of objects and a list of property names.\n\n- Use `Object.keys()`, `Array.prototype.filter()`, `Array.prototype.includes()` and `Array.prototype.reduce()` to produce a `filteredData` array, containing all objects with the keys specified in `propertyNames`.\n- Render a `<table>` element with a set of columns equal to the amount of values in `propertyNames`.\n- Use `Array.prototype.map` to render each value in the `propertyNames` array as a `<th>` element.\n- Use `Array.prototype.map` to render each object in the `filteredData` array as a `<tr>` element, containing a `<td>` for each key in the object.\n\n_This component does not work with nested objects and will break if there are nested objects inside any of the properties specified in `propertyNames`_\n\n",
"codeBlocks": {
"style": "",
"code": "function MappedTable({ data, propertyNames }) {\n let filteredData = data.map(v =>\n Object.keys(v)\n .filter(k => propertyNames.includes(k))\n .reduce((acc, key) => ((acc[key] = v[key]), acc), {})\n );\n return (\n <table>\n <thead>\n <tr>\n {propertyNames.map(val => (\n <th key={`h_${val}`}>{val}</th>\n ))}\n </tr>\n </thead>\n <tbody>\n {filteredData.map((val, i) => (\n <tr key={`i_${i}`}>\n {propertyNames.map(p => (\n <td key={`i_${i}_${p}`}>{val[p]}</td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n );\n}",
"example": "const people = [\n { name: 'John', surname: 'Smith', age: 42 },\n { name: 'Adam', surname: 'Smith', gender: 'male' }\n];\nconst propertyNames = ['name', 'surname', 'age'];\nReactDOM.render(\n <MappedTable data={people} propertyNames={propertyNames} />,\n document.getElementById('root')\n);"
},
"tags": [
"array",
"object",
"intermediate"
]
},
"meta": {
"hash": "fce03ceb446e80f63f4b1423c70dc854f4dbf38bb54a68302c2e09d9a2c8d402",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "Modal",
"title": "Modal",
"type": "snippet",
"attributes": {
"fileName": "Modal.md",
"text": "Renders a Modal component, controllable through events.\nTo use the component, import `Modal` only once and then display it by passing a boolean value to the `isVisible` attribute.\n\n- Use object destructuring to set defaults for certain attributes of the modal component.\n- Define `keydownHandler`, a method which handles all keyboard events, which can be used according to your needs to dispatch actions (e.g. close the modal when <kbd>Esc</kbd> is pressed).\n- Use `React.useEffect()` hook to add or remove the `keydown` event listener, which calls `keydownHandler`.\n- Use the `isVisible` prop to determine if the modal should be shown or not.\n- Use CSS to style and position the modal component.\n\n",
"codeBlocks": {
"style": ".modal {\n position: fixed;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n width: 100%;\n z-index: 9999;\n display: flex;\n align-items: center;\n justify-content: center;\n background-color: rgba(0, 0, 0, 0.25);\n animation-name: appear;\n animation-duration: 300ms;\n}\n\n.modal-dialog {\n width: 100%;\n max-width: 550px;\n background: white;\n position: relative;\n margin: 0 20px;\n max-height: calc(100vh - 40px);\n text-align: left;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);\n -webkit-animation-name: animatetop;\n -webkit-animation-duration: 0.4s;\n animation-name: slide-in;\n animation-duration: 0.5s;\n}\n\n.modal-header,\n.modal-footer {\n display: flex;\n align-items: center;\n padding: 1rem;\n}\n.modal-header {\n border-bottom: 1px solid #dbdbdb;\n justify-content: space-between;\n}\n.modal-footer {\n border-top: 1px solid #dbdbdb;\n justify-content: flex-end;\n}\n.modal-close {\n cursor: pointer;\n padding: 1rem;\n margin: -1rem -1rem -1rem auto;\n}\n.modal-body {\n overflow: auto;\n}\n.modal-content {\n padding: 1rem;\n}\n\n@keyframes appear {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n@keyframes slide-in {\n from {\n transform: translateY(-150px);\n }\n to {\n transform: translateY(0);\n }\n}",
"code": "function Modal({ isVisible = false, title, content, footer, onClose }) {\n React.useEffect(() => {\n document.addEventListener('keydown', keydownHandler);\n return () => document.removeEventListener('keydown', keydownHandler);\n });\n\n function keydownHandler({ key }) {\n switch (key) {\n case 'Escape':\n onClose();\n break;\n default:\n }\n }\n\n return !isVisible ? null : (\n <div className=\"modal\" onClick={onClose}>\n <div className=\"modal-dialog\" onClick={e => e.stopPropagation()}>\n <div className=\"modal-header\">\n <h3 className=\"modal-title\">{title}</h3>\n <span className=\"modal-close\" onClick={onClose}>\n &times;\n </span>\n </div>\n <div className=\"modal-body\">\n <div className=\"modal-content\">{content}</div>\n </div>\n {footer && <div className=\"modal-footer\">{footer}</div>}\n </div>\n </div>\n );\n}",
"example": "//Add the component to the render function\nfunction App() {\n const [isModal, setModal] = React.useState(false);\n\n return (\n <React.Fragment>\n <button onClick={() => setModal(true)}>Click Here</button>\n <Modal\n isVisible={isModal}\n title=\"Modal Title\"\n content={<p>Add your content here</p>}\n footer={<button>Cancel</button>}\n onClose={() => setModal(false)}\n />\n </React.Fragment>\n );\n}\n\nReactDOM.render(<App />, document.getElementById('root'));"
},
"tags": [
"visual",
"effect",
"intermediate"
]
},
"meta": {
"hash": "bbe8b37ec2d9ee322d89b28d0ac290efd7f5b1e501cad63bbf0674cbea9e2abc",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "MultiselectCheckbox",
"title": "MultiselectCheckbox",
"type": "snippet",
"attributes": {
"fileName": "MultiselectCheckbox.md",
"text": "Renders a checkbox list that uses a callback function to pass its selected value/values to the parent component.\n\n- Use `React.setState()` to create a `data` state variable and set its initial value equal to the `options` prop.\n- Create a function `toggle` that is used to toggle the `checked` to update the `data` state variable and call the `onChange` callback passed via the component's props.\n- Render a `<ul>` element and use `Array.prototype.map()` to map the `data` state variable to individual `<li>` elements with `<input>` elements as their children.\n- Each `<input>` element has the `type='checkbox'` attribute and is marked as `readOnly`, as its click events are handled by the parent `<li>` element's `onClick` handler.\n\n",
"codeBlocks": {
"style": "",
"code": "const style = {\n listContainer: {\n listStyle: 'none',\n paddingLeft: 0\n },\n itemStyle: {\n cursor: 'pointer',\n padding: 5\n }\n};\n\nfunction MultiselectCheckbox({ options, onChange }) {\n const [data, setData] = React.useState(options);\n\n const toggle = item => {\n data.forEach((_, key) => {\n if (data[key].label === item.label) data[key].checked = !item.checked;\n });\n setData([...data]);\n onChange(data);\n };\n\n return (\n <ul style={style.listContainer}>\n {data.map(item => {\n return (\n <li key={item.label} style={style.itemStyle} onClick={() => toggle(item)}>\n <input readOnly type=\"checkbox\" checked={item.checked || false} />\n {item.label}\n </li>\n );\n })}\n </ul>\n );\n}",
"example": "const options = [{ label: 'Item One' }, { label: 'Item Two' }];\n\nReactDOM.render(\n <MultiselectCheckbox\n options={options}\n onChange={data => {\n console.log(data);\n }}\n />,\n document.getElementById('root')\n);"
},
"tags": [
"input",
"state",
"array",
"intermediate"
]
},
"meta": {
"hash": "723cc4aeb42bc0234045688334e01ec89b66782a54862d2b2236ae12e1f87881",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "PasswordRevealer",
"title": "PasswordRevealer",
"type": "snippet",
"attributes": {
"fileName": "PasswordRevealer.md",
"text": "Renders a password input field with a reveal button.\n\n- Use the `React.useState()` hook to create the `shown` state variable and set its value to `false`.\n- Use a`<div>` to wrap both the`<input>` and the `<button>` element that toggles the type of the input field between `\"text\"` and `\"password\"`.\n\n",
"codeBlocks": {
"style": "",
"code": "function PasswordRevealer({ value }) {\n const [shown, setShown] = React.useState(false);\n\n return (\n <div>\n <input type={shown ? 'text' : 'password'} value={value} onChange={() => {}} />\n <button onClick={() => setShown(!shown)}>Show/Hide</button>\n </div>\n );\n}",
"example": "ReactDOM.render(<PasswordRevealer />, document.getElementById('root'));"
},
"tags": [
"input",
"state",
"beginner"
]
},
"meta": {
"hash": "b9d1d5a6b61d2ab8e73943da1dcf86bfa872821c9584715a2cee303a052334ea",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "RippleButton",
"title": "RippleButton",
"type": "snippet",
"attributes": {
"fileName": "RippleButton.md",
"text": "Renders a button that animates a ripple effect when clicked.\n\n- Define some appropriate CSS styles and an animation for the ripple effect.\n- Use the `React.useState()` hook to create appropriate variables and setters for the pointer's coordinates and for the animation state of the button.\n- Use the `React.useEffect()` hook to change the state every time the `coords` state variable changes, starting the animation.\n- Use `setTimeout()` in the previous hook to clear the animation after it's done playing.\n- Use the `React.useEffect()` hook a second time to reset `coords` whenever the `isRippling` state variable is `false.`\n- Handle the `onClick` event by updating the `coords` state variable and calling the passed callback.\n- Finally, render a `<button>` with one or two `<span>` elements, setting the position of the `.ripple` element based on the `coords` state variable.\n\n",
"codeBlocks": {
"style": ".ripple-button {\n border-radius: 4px;\n border: none;\n margin: 8px;\n padding: 14px 24px;\n background: #1976d2;\n color: #fff;\n overflow: hidden;\n position: relative;\n cursor: pointer;\n}\n\n.ripple-button > .ripple {\n width: 20px;\n height: 20px;\n position: absolute;\n background: #63a4ff;\n display: block;\n content: \"\";\n border-radius: 9999px;\n opacity: 1;\n animation: 1.2s ease 1 forwards ripple-effect;\n}\n\n@keyframes ripple-effect {\n 0% {\n transform: scale(1);\n opacity: 1;\n }\n 50% {\n transform: scale(10);\n opacity: 0.375;\n }\n 100% {\n transform: scale(35);\n opacity: 0;\n }\n}\n\n.ripple-button > .content {\n position: relative;\n z-index: 2;\n}",
"code": "function RippleButton({ children, onClick }) {\n const [coords, setCoords] = React.useState({ x: -1, y: -1 });\n const [isRippling, setIsRippling] = React.useState(false);\n\n React.useEffect(\n () => {\n if (coords.x !== -1 && coords.y !== -1) {\n setIsRippling(true);\n setTimeout(() => setIsRippling(false), 1200);\n } else setIsRippling(false);\n },\n [coords]\n );\n\n React.useEffect(\n () => {\n if (!isRippling) setCoords({ x: -1, y: -1 });\n },\n [isRippling]\n );\n\n return (\n <button\n className=\"ripple-button\"\n onClick={e => {\n var rect = e.target.getBoundingClientRect();\n var x = e.clientX - rect.left;\n var y = e.clientY - rect.top;\n setCoords({ x, y });\n onClick && onClick(e);\n }}\n >\n {isRippling ? (\n <span\n className=\"ripple\"\n style={{\n left: coords.x + 10,\n top: coords.y\n }}\n />\n ) : (\n \"\"\n )}\n <span className=\"content\">{children}</span>\n </button>\n );\n}",
"example": "ReactDOM.render(\n <RippleButton onClick={e => console.log(e)}>Click me</RippleButton>,\n document.getElementById('root')\n);"
},
"tags": [
"visual",
"state",
"effect",
"intermediate"
]
},
"meta": {
"hash": "a2238ea3abedb5a38d836a57966006cc43f905b375836d138bd69671a8731d84",
"firstSeen": "1568095649",
"lastUpdated": "1568182395",
"updateCount": 3
}
},
{
"id": "Select",
"title": "Select",
"type": "snippet",
"attributes": {
"fileName": "Select.md",
"text": "Renders a `<select>` element that uses a callback function to pass its value to the parent component.\n\n- Use object destructuring to set defaults for certain attributes of the `<select>` element.\n- Render a `<select>` element with the appropriate attributes and use the `callback` function in the `onChange` event to pass the value of the textarea to the parent.\n- Use destructuring on the `values` array to pass an array of `value` and `text` elements and the `selected` attribute to define the initial `value` of the `<select>` element.\n\n",
"codeBlocks": {
"style": "",
"code": "function Select({ values, callback, disabled = false, readonly = false, selected }) {\n return (\n <select\n disabled={disabled}\n readOnly={readonly}\n onChange={({ target: { value } }) => callback(value)}\n >\n {values.map(([value, text]) => (\n <option selected={selected === value} value={value}>\n {text}\n </option>\n ))}\n </select>\n );\n}",
"example": "let choices = [\n ['grapefruit', 'Grapefruit'],\n ['lime', 'Lime'],\n ['coconut', 'Coconut'],\n ['mango', 'Mango']\n];\nReactDOM.render(\n <Select values={choices} selected=\"lime\" callback={val => console.log(val)} />,\n document.getElementById('root')\n);"
},
"tags": [
"input",
"beginner"
]
},
"meta": {
"hash": "82ec17f203f168e42206f2a56a5954e01fd639599f26cc1c8bafb77fb5b5fb5b",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "Slider",
"title": "Slider",
"type": "snippet",
"attributes": {
"fileName": "Slider.md",
"text": "Renders a slider element that uses a callback function to pass its value to the parent component.\n\n- Use object destructuring to set defaults for certain attributes of the `<input>` element.\n- Render an `<input>` element of type `\"range\"` and the appropriate attributes, use the `callback` function in the `onChange` event to pass the value of the input to the parent.\n\n",
"codeBlocks": {
"style": "",
"code": "function Slider({ callback, disabled = false, readOnly = false }) {\n return (\n <input\n type=\"range\"\n disabled={disabled}\n readOnly={readOnly}\n onChange={({ target: { value } }) => callback(value)}\n />\n );\n}",
"example": "ReactDOM.render(<Slider callback={val => console.log(val)} />, document.getElementById('root'));"
},
"tags": [
"input",
"beginner"
]
},
"meta": {
"hash": "bf2bc45d4c4781f54cee33599c17b35bd4ce6a90e70dd5305401e2b4bafa21bf",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "StarRating",
"title": "StarRating",
"type": "snippet",
"attributes": {
"fileName": "StarRating.md",
"text": "Renders a star rating component.\n\n- Define a component, called `Star` that will render each individual star with the appropriate appearance, based on the parent component's state.\n- In the `StarRating` component, use the `React.useState()` hook to define the `rating` and `selection` state variables with the initial values of `props.rating` (or `0` if invalid or not supplied) and `0`.\n- Create a method, `hoverOver`, that updates `selected` and `rating` according to the provided `event`.\n- Create a `<div>` to wrap the `<Star>` components, which are created using `Array.prototype.map` on an array of 5 elements, created using `Array.from`, and handle the `onMouseLeave` event to set `selection` to `0`, the `onClick` event to set the `rating` and the `onMouseOver` event to set `selection` to the `star-id` attribute of the `event.target` respectively.\n- Finally, pass the appropriate values to each `<Star>` component (`starId` and `marked`).\n\n",
"codeBlocks": {
"style": "",
"code": "function Star({ marked, starId }) {\n return (\n <span star-id={starId} style={{ color: '#ff9933' }} role=\"button\">\n {marked ? '\\u2605' : '\\u2606'}\n </span>\n );\n}\n\nfunction StarRating(props) {\n const [rating, setRating] = React.useState(typeof props.rating == 'number' ? props.rating : 0);\n const [selection, setSelection] = React.useState(0);\n const hoverOver = event => {\n let val = 0;\n if (event && event.target && event.target.getAttribute('star-id'))\n val = event.target.getAttribute('star-id');\n setSelection(val);\n };\n return (\n <div\n onMouseOut={() => hoverOver(null)}\n onClick={event => setRating(event.target.getAttribute('star-id') || rating)}\n onMouseOver={hoverOver}\n >\n {Array.from({ length: 5 }, (v, i) => (\n <Star\n starId={i + 1}\n key={`star_${i + 1} `}\n marked={selection ? selection >= i + 1 : rating >= i + 1}\n />\n ))}\n </div>\n );\n}",
"example": "ReactDOM.render(<StarRating />, document.getElementById('root'));\nReactDOM.render(<StarRating rating={2} />, document.getElementById('root'));"
},
"tags": [
"visual",
"children",
"input",
"state",
"intermediate"
]
},
"meta": {
"hash": "1925a397f77ea80ee9dc9d82acee6dc279a3e82abac815b32109ce930de20a1f",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "Tabs",
"title": "Tabs",
"type": "snippet",
"attributes": {
"fileName": "Tabs.md",
"text": "Renders a tabbed menu and view component.\n\n- Define a `TabItem` component, pass it to the `Tab` and remove unnecessary nodes expect for `TabItem` by identifying the function's name in `props.children`.\n- Use the `React.useState()` hook to initialize the value of the `bindIndex` state variable to `props.defaultIndex`.\n- Use `Array.prototype.map` on the collected nodes to render the `tab-menu` and `tab-view`.\n- Define `changeTab`, which will be executed when clicking a `<button>` from the `tab-menu`.\n- `changeTab` executes the passed callback, `onTabClick` and updates `bindIndex`, which in turn causes a re-render, evaluating the `style` and `className` of the `tab-view` items and `tab-menu` buttons according to their `index`.\n\n",
"codeBlocks": {
"style": ".tab-menu > button {\n cursor: pointer;\n padding: 8px 16px;\n border: 0;\n border-bottom: 2px solid transparent;\n background: none;\n}\n.tab-menu > button.focus {\n border-bottom: 2px solid #007bef;\n}\n.tab-menu > button:hover {\n border-bottom: 2px solid #007bef;\n}",
"code": "function TabItem(props) {\n return <div {...props} />;\n}\n\nfunction Tabs(props) {\n const [bindIndex, setBindIndex] = React.useState(props.defaultIndex);\n const changeTab = newIndex => {\n if (typeof props.onTabClick === 'function') props.onTabClick(newIndex);\n setBindIndex(newIndex);\n };\n const items = props.children.filter(item => item.type.name === 'TabItem');\n\n return (\n <div className=\"wrapper\">\n <div className=\"tab-menu\">\n {items.map(({ props: { index, label } }) => (\n <button onClick={() => changeTab(index)} className={bindIndex === index ? 'focus' : ''}>\n {label}\n </button>\n ))}\n </div>\n <div className=\"tab-view\">\n {items.map(({ props }) => (\n <div\n {...props}\n className=\"tab-view_item\"\n key={props.index}\n style={{ display: bindIndex === props.index ? 'block' : 'none' }}\n />\n ))}\n </div>\n </div>\n );\n}",
"example": "ReactDOM.render(\n <Tabs defaultIndex=\"1\" onTabClick={console.log}>\n <TabItem label=\"A\" index=\"1\">\n Lorem ipsum\n </TabItem>\n <TabItem label=\"B\" index=\"2\">\n Dolor sit amet\n </TabItem>\n </Tabs>,\n document.getElementById('root')\n);"
},
"tags": [
"visual",
"state",
"children",
"intermediate"
]
},
"meta": {
"hash": "9f8634ca4a5f49134cb88e00c0f193c6c6c5cf8ee60482a16782c04f48595176",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "TagInput",
"title": "TagInput",
"type": "snippet",
"attributes": {
"fileName": "TagInput.md",
"text": "Renders a tag input field.\n\n- Define a `TagInput` component and use `React.useState()` hook to initialize an array with tags passed as `props`.\n- Use `Array.prototype.map()` on collected nodes to render the list of tags.\n- Define the `addTags` method, which will be executed on pressing the `Enter` key.\n- The `addTags` method uses the `setTags` method to add the new tag using the spread (`...`) operator to prepend the existing tags and adds the new tag at the end of the `tags` array.\n- Define the `removeTags` method, which will be executed on clicking the delete icon in the tag.\n- Use `Array.prototype.filter()` in `removeTags` method to remove the tag using the `index` of the tag to filter it out from `tags` array.\n\n",
"codeBlocks": {
"style": ".tag-input {\n display: flex;\n flex-wrap: wrap;\n min-height: 48px;\n padding: 0 8px;\n border: 1px solid #d6d8da;\n border-radius: 6px;\n}\n.tag-input input {\n flex: 1;\n border: none;\n height: 46px;\n font-size: 14px;\n padding: 4px 0 0;\n &:focus {\n outline: transparent;\n }\n}\n#tags {\n display: flex;\n flex-wrap: wrap;\n padding: 0;\n margin: 8px 0 0;\n}\n.tag {\n width: auto;\n height: 32px;\n display: flex;\n align-items: center;\n justify-content: center;\n color: #fff;\n padding: 0 8px;\n font-size: 14px;\n list-style: none;\n border-radius: 6px;\n margin: 0 8px 8px 0;\n background: #0052cc;\n}\n.tag-title {\n margin-top: 3px;\n}\n.tag-close-icon {\n display: block;\n width: 16px;\n height: 16px;\n line-height: 16px;\n text-align: center;\n font-size: 14px;\n margin-left: 8px;\n color: #0052cc;\n border-radius: 50%;\n background: #fff;\n cursor: pointer;\n}",
"code": "function TagInput(props) {\n const [tags, setTags] = React.useState(props.tags);\n const removeTags = indexToRemove => {\n setTags([...tags.filter((_, index) => index !== indexToRemove)]);\n };\n const addTags = event => {\n if (event.target.value !== \"\") {\n setTags([...tags, event.target.value]);\n event.target.value = \"\";\n }\n };\n return (\n <div className=\"tag-input\">\n <ul id=\"tags\">\n {tags.map((tag, index) => (\n <li key={index} className=\"tag\">\n <span className=\"tag-title\">{tag}</span>\n <span className=\"tag-close-icon\" onClick={() => removeTags(index)}>\n x\n </span>\n </li>\n ))}\n </ul>\n <input\n type=\"text\"\n onKeyUp={event => (event.key === \"Enter\" ? addTags(event) : null)}\n placeholder=\"Press enter to add tags\"\n />\n </div>\n );\n}",
"example": "ReactDOM.render(<TagInput tags={['Nodejs', 'MongoDB']}/>, document.getElementById('root'));"
},
"tags": [
"input",
"visual",
"state",
"intermediate"
]
},
"meta": {
"hash": "495a9ac0a38fd1cf16c5873d4533c1084f35cbd2a61c8c3b123e14e85c50c764",
"firstSeen": "1569999971",
"lastUpdated": "1570792845",
"updateCount": 9
}
},
{
"id": "TextArea",
"title": "TextArea",
"type": "snippet",
"attributes": {
"fileName": "TextArea.md",
"text": "Renders a `<textarea>` element that uses a callback function to pass its value to the parent component.\n\n- Use object destructuring to set defaults for certain attributes of the `<textarea>` element.\n- Render a `<textarea>` element with the appropriate attributes and use the `callback` function in the `onChange` event to pass the value of the textarea to the parent.\n\n",
"codeBlocks": {
"style": "",
"code": "function TextArea({\n callback,\n cols = 20,\n rows = 2,\n disabled = false,\n readOnly = false,\n placeholder = ''\n}) {\n return (\n <textarea\n cols={cols}\n rows={rows}\n disabled={disabled}\n readOnly={readOnly}\n placeholder={placeholder}\n onChange={({ target: { value } }) => callback(value)}\n />\n );\n}",
"example": "ReactDOM.render(\n <TextArea placeholder=\"Insert some text here...\" callback={val => console.log(val)} />,\n document.getElementById('root')\n);"
},
"tags": [
"input",
"beginner"
]
},
"meta": {
"hash": "a6ed5da811b5f42c139e0d0d868a0b49881203467ffcb464b707a0d9bbe7660f",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "Ticker",
"title": "Ticker",
"type": "snippet",
"attributes": {
"fileName": "Ticker.md",
"text": "Renders a ticker component.\n\n- Use the `React.useState()` hook to initialize the `ticker` state variable to `0`.\n- Define two methods, `tick` and `reset`, that will periodically increment `timer` based on `interval` and reset `interval` respectively.\n- Return a `<div>` with two `<button>` elements, each of which calls `tick` and `reset` respectively.\n\n",
"codeBlocks": {
"style": "",
"code": "function Ticker(props) {\n const [ticker, setTicker] = React.useState(0);\n let interval = null;\n\n const tick = () => {\n reset();\n interval = setInterval(() => {\n if (ticker < props.times) setTicker(ticker + 1);\n else clearInterval(interval);\n }, props.interval);\n };\n\n const reset = () => {\n setTicker(0);\n clearInterval(interval);\n };\n\n return (\n <div>\n <span style={{ fontSize: 100 }}>{ticker}</span>\n <button onClick={tick}>Tick!</button>\n <button onClick={reset}>Reset</button>\n </div>\n );\n}",
"example": "ReactDOM.render(<Ticker times={5} interval={1000} />, document.getElementById('root'));"
},
"tags": [
"visual",
"state",
"beginner"
]
},
"meta": {
"hash": "eb29bbedf8f0aed903abf2b12ce90b5d02a8b3fdae15b4c8810b5841aeca9e4b",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "Toggle",
"title": "Toggle",
"type": "snippet",
"attributes": {
"fileName": "Toggle.md",
"text": "Renders a toggle component.\n\n- Use the `React.useState()` to initialize the `isToggleOn` state variable to `false`.\n- Use an object, `style`, to hold the styles for individual components and their states.\n- Return a `<button>` that alters the component's `isToggledOn` when its `onClick` event is fired and determine the appearance of the content based on `isToggleOn`, applying the appropriate CSS rules from the `style` object.\n\n",
"codeBlocks": {
"style": "",
"code": "function Toggle(props) {\n const [isToggleOn, setIsToggleOn] = React.useState(false);\n style = {\n on: {\n backgroundColor: 'green'\n },\n off: {\n backgroundColor: 'grey'\n }\n };\n\n return (\n <button onClick={() => setIsToggleOn(!isToggleOn)} style={isToggleOn ? style.on : style.off}>\n {isToggleOn ? 'ON' : 'OFF'}\n </button>\n );\n}",
"example": "ReactDOM.render(<Toggle />, document.getElementById('root'));"
},
"tags": [
"visual",
"state",
"beginner"
]
},
"meta": {
"hash": "9a7a1630d12ccf86f0712a7ca7444698933f3f3d946957ef1b6202637c44d531",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "Tooltip",
"title": "Tooltip",
"type": "snippet",
"attributes": {
"fileName": "Tooltip.md",
"text": "Renders a tooltip component.\n\n- Use the `React.useState()` hook to create the `show` variable and initialize it to `false`.\n- Return a `<div>` element that contains the `<div>` that will be the tooltip and the `children` passed to the component.\n- Handle the `onMouseEnter` and `onMouseLeave` methods, by altering the value of the `show` variable.\n\n",
"codeBlocks": {
"style": ".tooltip {\n position: relative;\n background: rgba(0, 0, 0, 0.7);\n color: white;\n visibility: hidden;\n padding: 5px;\n border-radius: 5px;\n}\n.tooltip-arrow {\n position: absolute;\n top: 100%;\n left: 50%;\n border-width: 5px;\n border-style: solid;\n border-color: rgba(0, 0, 0, 0.7) transparent transparent;\n}",
"code": "function Tooltip({ children, text, ...rest }) {\n const [show, setShow] = React.useState(false);\n\n return (\n <div>\n <div className=\"tooltip\" style={show ? { visibility: 'visible' } : {}}>\n {text}\n <span className=\"tooltip-arrow\" />\n </div>\n <div {...rest} onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)}>\n {children}\n </div>\n </div>\n );\n}",
"example": "ReactDOM.render(\n <Tooltip text=\"Simple tooltip\">\n <button>Hover me!</button>\n </Tooltip>,\n document.getElementById('root')\n);"
},
"tags": [
"visual",
"state",
"children",
"beginner"
]
},
"meta": {
"hash": "1d29be55adf50919e115f5fa83d7446bd11688f4d3a50c19bf357675cd7fdfd4",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "TreeView",
"title": "TreeView",
"type": "snippet",
"attributes": {
"fileName": "TreeView.md",
"text": "Renders a tree view of a JSON object or array with collapsible content.\n\n- Use object destructuring to set defaults for certain props.\n- Use the value of the `toggled` prop to determine the initial state of the content (collapsed/expanded).\n- Use the `React.setState()` hook to create the `isToggled` state variable and give it the value of the `toggled` prop initially.\n- Return a `<div>` to wrap the contents of the component and the `<span>` element, used to alter the component's `isToggled` state.\n- Determine the appearance of the component, based on `isParentToggled`, `isToggled`, `name` and `Array.isArray()` on `data`.\n- For each child in `data`, determine if it is an object or array and recursively render a sub-tree.\n- Otherwise, render a `<p>` element with the appropriate style.\n\n",
"codeBlocks": {
"style": ".tree-element {\n margin: 0;\n position: relative;\n}\n\ndiv.tree-element:before {\n content: '';\n position: absolute;\n top: 24px;\n left: 1px;\n height: calc(100% - 48px);\n border-left: 1px solid gray;\n}\n\n.toggler {\n position: absolute;\n top: 10px;\n left: 0px;\n width: 0;\n height: 0;\n border-top: 4px solid transparent;\n border-bottom: 4px solid transparent;\n border-left: 5px solid gray;\n cursor: pointer;\n}\n\n.toggler.closed {\n transform: rotate(90deg);\n}\n\n.collapsed {\n display: none;\n}",
"code": "function TreeView({\n data,\n toggled = true,\n name = null,\n isLast = true,\n isChildElement = false,\n isParentToggled = true\n}) {\n const [isToggled, setIsToggled] = React.useState(toggled);\n\n return (\n <div\n style={{ marginLeft: isChildElement ? 16 : 4 + 'px' }}\n className={isParentToggled ? 'tree-element' : 'tree-element collapsed'}\n >\n <span\n className={isToggled ? 'toggler' : 'toggler closed'}\n onClick={() => setIsToggled(!isToggled)}\n />\n {name ? <strong>&nbsp;&nbsp;{name}: </strong> : <span>&nbsp;&nbsp;</span>}\n {Array.isArray(data) ? '[' : '{'}\n {!isToggled && '...'}\n {Object.keys(data).map((v, i, a) =>\n typeof data[v] == 'object' ? (\n <TreeView\n data={data[v]}\n isLast={i === a.length - 1}\n name={Array.isArray(data) ? null : v}\n isChildElement\n isParentToggled={isParentToggled && isToggled}\n />\n ) : (\n <p\n style={{ marginLeft: 16 + 'px' }}\n className={isToggled ? 'tree-element' : 'tree-element collapsed'}\n >\n {Array.isArray(data) ? '' : <strong>{v}: </strong>}\n {data[v]}\n {i === a.length - 1 ? '' : ','}\n </p>\n )\n )}\n {Array.isArray(data) ? ']' : '}'}\n {!isLast ? ',' : ''}\n </div>\n );\n}",
"example": "let data = {\n lorem: {\n ipsum: 'dolor sit',\n amet: {\n consectetur: 'adipiscing',\n elit: [\n 'duis',\n 'vitae',\n {\n semper: 'orci'\n },\n {\n est: 'sed ornare'\n },\n 'etiam',\n ['laoreet', 'tincidunt'],\n ['vestibulum', 'ante']\n ]\n },\n ipsum: 'primis'\n }\n};\nReactDOM.render(<TreeView data={data} name=\"data\" />, document.getElementById('root'));"
},
"tags": [
"visual",
"object",
"state",
"recursion",
"advanced"
]
},
"meta": {
"hash": "63922e84d527dc7783025495ebab1df55452b595d0a5e54981d8ea891e055736",
"firstSeen": "1566386637",
"lastUpdated": "1566387025",
"updateCount": 3
}
},
{
"id": "UncontrolledInput",
"title": "UncontrolledInput",
"type": "snippet",
"attributes": {
"fileName": "UncontrolledInput.md",
"text": "Renders an `<input>` element that uses a callback function to pass its value to the parent component.\n\n- Use object destructuring to set defaults for certain attributes of the `<input>` element.\n- Render an `<input>` element with the appropriate attributes and use the `callback` function in the `onChange` event to pass the value of the input to the parent.\n\n",
"codeBlocks": {
"style": "",
"code": "function UncontrolledInput({\n callback,\n type = 'text',\n disabled = false,\n readOnly = false,\n placeholder = ''\n}) {\n return (\n <input\n type={type}\n disabled={disabled}\n readOnly={readOnly}\n placeholder={placeholder}\n onChange={({ target: { value } }) => callback(value)}\n />\n );\n}",
"example": "ReactDOM.render(\n <UncontrolledInput\n type=\"text\"\n placeholder=\"Insert some text here...\"\n callback={val => console.log(val)}\n />,\n document.getElementById('root')\n);"
},
"tags": [
"input",
"beginner"
]
},
"meta": {
"hash": "11581e3b40209c7152833aa421c7d18c889b16067c5cc1557b1bb7f604f18982",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "useClickInside",
"title": "useClickInside",
"type": "snippet",
"attributes": {
"fileName": "useClickInside.md",
"text": "A hook that handles the event of clicking inside the wrapped component.\n\n- Create a custom hook that takes a `ref` and a `callback` to handle the `click` event.\n- Use the `React.useEffect()` hook to append and clean up the `click` event.\n- Use the `React.useRef()` hook to create a `ref` for your click component and pass it to the `useClickInside` hook.\n\n",
"codeBlocks": {
"style": "",
"code": "const useClickInside = (ref, callback) => {\n const handleClick = e => {\n if (ref.current && ref.current.contains(e.target)) {\n callback();\n }\n };\n React.useEffect(() => {\n document.addEventListener('click', handleClick);\n return () => {\n document.removeEventListener('click', handleClick);\n };\n });\n};",
"example": "const ClickBox = ({ onClickInside }) => {\n const clickRef = React.useRef();\n useClickInside(clickRef, onClickInside);\n return (\n <div\n className=\"click-box\"\n ref={clickRef}\n style={{\n border: '2px dashed orangered',\n height: 200,\n width: 400,\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center'\n }}\n >\n <p>Click inside this element</p>\n </div>\n );\n};\n\nReactDOM.render(\n <ClickBox onClickInside={() => alert('click inside')} />,\n document.getElementById('root')\n);"
},
"tags": [
"hooks",
"effect",
"event",
"intermediate"
]
},
"meta": {
"hash": "1be6623c673a30671e534ac363e5acffdedc8d890fad5f73a7cafc7c7402bb75",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "useClickOutside",
"title": "useClickOutside",
"type": "snippet",
"attributes": {
"fileName": "useClickOutside.md",
"text": "A hook that handles the event of clicking outside of the wrapped component.\n\n- Create a custom hook that takes a `ref` and a `callback` to handle the `click` event.\n- Use the `React.useEffect()` hook to append and clean up the `click` event.\n- Use the `React.useRef()` hook to create a `ref` for your click component and pass it to the `useClickOutside` hook.\n\n",
"codeBlocks": {
"style": "",
"code": "const useClickOutside = (ref, callback) => {\n const handleClick = e => {\n if (ref.current && !ref.current.contains(e.target)) {\n callback();\n }\n };\n React.useEffect(() => {\n document.addEventListener('click', handleClick);\n return () => {\n document.removeEventListener('click', handleClick);\n };\n });\n};",
"example": "const ClickBox = ({ onClickOutside }) => {\n const clickRef = React.useRef();\n useClickOutside(clickRef, onClickOutside);\n return (\n <div\n className=\"click-box\"\n ref={clickRef}\n style={{\n border: '2px dashed orangered',\n height: 200,\n width: 400,\n display: 'flex',\n justifyContent: 'center',\n alignItems: 'center'\n }}\n >\n <p>Click out of this element</p>\n </div>\n );\n};\n\nReactDOM.render(\n <ClickBox onClickOutside={() => alert('click outside')} />,\n document.getElementById('root')\n);"
},
"tags": [
"hooks",
"effect",
"event",
"intermediate"
]
},
"meta": {
"hash": "e565a610582386df7a41cbcfcd2d2ad7df11651adceafdd9e4840ca2b756af21",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "useFetch",
"title": "useFetch",
"type": "snippet",
"attributes": {
"fileName": "useFetch.md",
"text": "A hook that implements `fetch` in a declarative manner.\n\n- Create a custom hook that takes a `url` and `options`.\n- Use the `React.useState()` hook to initialize the `response` and `error` state variables.\n- Use the `React.useEffect()` hook to anychronously call `fetch()` and update the state varaibles accordingly.\n- Return an object containting the `response` and `error` state variables.\n\n",
"codeBlocks": {
"style": "",
"code": "const useFetch = (url, options) => {\n const [response, setResponse] = React.useState(null);\n const [error, setError] = React.useState(null);\n\n React.useEffect(() => {\n const fetchData = async () => {\n try {\n const res = await fetch(url, options);\n const json = await res.json();\n setResponse(json);\n } catch (error) {\n setError(error);\n }\n };\n fetchData();\n }, []);\n\n return { response, error };\n};",
"example": "const ImageFetch = props => {\n const res = useFetch('https://dog.ceo/api/breeds/image/random', {});\n if (!res.response) {\n return <div>Loading...</div>;\n }\n const dogName = res.response.status;\n const imageUrl = res.response.message;\n return (\n <div>\n <img src={imageUrl} alt=\"avatar\" width={400} height=\"auto\" />\n </div>\n );\n};\n\nReactDOM.render(<ImageFetch />, document.getElementById('root'));"
},
"tags": [
"hooks",
"effect",
"state",
"intermediate"
]
},
"meta": {
"hash": "2b621b216e6f8225c435deff5ca567628e97c5a39bb20f5b19c92f521a8a8f0c",
"firstSeen": "1566386637",
"lastUpdated": "1566386637",
"updateCount": 2
}
},
{
"id": "useInterval",
"title": "useInterval",
"type": "snippet",
"attributes": {
"fileName": "useInterval.md",
"text": "A hook that implements `setInterval` in a declarative manner.\n\n- Create a custom hook that takes a `callback` and a `delay`.\n- Use the `React.useRef()` hook to create a `ref` for the callback function.\n- Use the `React.useEffect()` hook to remember the latest callback.\n- Use the `React.useEffect()` hook to set up the interval and clean up.\n\n",
"codeBlocks": {
"style": "",
"code": "const useInterval = (callback, delay) => {\n const savedCallback = React.useRef();\n\n React.useEffect(() => {\n savedCallback.current = callback;\n }, [callback]);\n\n React.useEffect(() => {\n function tick() {\n savedCallback.current();\n }\n if (delay !== null) {\n let id = setInterval(tick, delay);\n return () => clearInterval(id);\n }\n }, [delay]);\n};",
"example": "const Timer = props => {\n const [seconds, setSeconds] = React.useState(0);\n useInterval(() => {\n setSeconds(seconds + 1);\n }, 1000);\n\n return <p>{seconds}</p>;\n};\n\nReactDOM.render(<Timer />, document.getElementById('root'));"
},
"tags": [
"hooks",
"effect",
"intermediate"
]
},
"meta": {
"hash": "2146f00ffd55bd78f63e0543922b73cdc339acf728067bf96f20c05eca5306ab",
"firstSeen": "1566386637",
"lastUpdated": "1567858543",
"updateCount": 3
}
},
{
"id": "useNavigatorOnLine",
"title": "useNavigatorOnLine",
"type": "snippet",
"attributes": {
"fileName": "useNavigatorOnLine.md",
"text": "A hook that returns if the client is online or offline.\n\n- Create a function, `getOnLineStatus`, that uses the `NavigatorOnLine` web API to get the online status of the client.\n- Use the `React.useState()` hook to create an appropriate state variable, `status`, and setter.\n- Use the `React.useEffect()` hook to add listeners for appropriate events, updating state, and cleanup those listeners when unmounting.\n- Finally return the `status` state variable.\n\n",
"codeBlocks": {
"style": "",
"code": "const getOnLineStatus = () =>\n typeof navigator !== \"undefined\" && typeof navigator.onLine === \"boolean\"\n ? navigator.onLine\n : true;\n\nconst useNavigatorOnLine = () => {\n const [status, setStatus] = React.useState(getOnLineStatus());\n\n const setOnline = () => setStatus(true);\n const setOffline = () => setStatus(false);\n\n React.useEffect(() => {\n window.addEventListener(\"online\", setOnline);\n window.addEventListener(\"offline\", setOffline);\n\n return () => {\n window.removeEventListener(\"online\", setOnline);\n window.removeEventListener(\"offline\", setOffline);\n };\n }, []);\n\n return status;\n};",
"example": "const StatusIndicator = () => {\n const isOnline = useNavigatorOnLine();\n\n return <span>You are {isOnline ? \"online\" : \"offline\"}.</span>;\n};\n\nReactDOM.render(<StatusIndicator />, document.getElementById(\"root\"));"
},
"tags": [
"hooks",
"state",
"effect",
"intermediate"
]
},
"meta": {
"hash": "c9a0c97f92439438fd49c5ef50742524aae8a162e144342956bcf92cf1ebf470",
"firstSeen": "1568182646",
"lastUpdated": "1568182646",
"updateCount": 2
}
},
{
"id": "useSSR",
"title": "useSSR",
"type": "snippet",
"attributes": {
"fileName": "useSSR.md",
"text": "A hook that checks if the code is running on the browser or the server.\n\n- Create a custom hook that returns an appropriate object.\n- Use `typeof window`, `window.document` and `window.document.createElement` to check if the code is running on the browser.\n- Use the `React.useState()` hook to define the `inBrowser` state variable.\n- Use the `React.useEffect()` hook to update the `inBrowser` state variable and clean up at the end.\n- Use the `React.useMemo()` to memoize the return values of the custom hook.\n\n",
"codeBlocks": {
"style": "",
"code": "const isDOMavailable = !!(\n typeof window !== 'undefined' &&\n window.document &&\n window.document.createElement\n);\n\nconst useSSR = (callback, delay) => {\n const [inBrowser, setInBrowser] = React.useState(isDOMavailable);\n\n React.useEffect(() => {\n setInBrowser(isDOMavailable);\n return () => {\n setInBrowser(false);\n }\n }, []);\n\n const useSSRObject = React.useMemo(() => ({\n isBrowser: inBrowser,\n isServer: !inBrowser,\n canUseWorkers: typeof Worker !== 'undefined',\n canUseEventListeners: inBrowser && !!window.addEventListener,\n canUseViewport: inBrowser && !!window.screen\n }), [inBrowser]);\n\n return React.useMemo(() => Object.assign(Object.values(useSSRObject), useSSRObject), [inBrowser]);\n};",
"example": "const SSRChecker = props => {\n let { isBrowser, isServer } = useSSR();\n\n return <p>{ isBrowser ? 'Running on browser' : 'Running on server' }</p>;\n};\n\nReactDOM.render(<SSRChecker />, document.getElementById('root'));"
},
"tags": [
"hooks",
"effect",
"state",
"memo",
"intermediate"
]
},
"meta": {
"hash": "e55822c285e99c1aded28e5c8910080c5a0bb9878931d97c6dbc4d5d24ec9fe7",
"firstSeen": "1566641896",
"lastUpdated": "1574090380",
"updateCount": 3
}
},
{
"id": "useTimeout",
"title": "useTimeout",
"type": "snippet",
"attributes": {
"fileName": "useTimeout.md",
"text": "A hook that implements `setTimeout` in a declarative manner.\n\n- Create a custom hook that takes a `callback` and a `delay`.\n- Use the `React.useRef()` hook to create a `ref` for the callback function.\n- Use the `React.useEffect()` hook to remember the latest callback.\n- Use the `React.useEffect()` hook to set up the timeout and clean up.\n\n",
"codeBlocks": {
"style": "",
"code": "const useTimeout = (callback, delay) => {\n const savedCallback = React.useRef();\n\n React.useEffect(() => {\n savedCallback.current = callback;\n }, [callback]);\n\n React.useEffect(() => {\n function tick() {\n savedCallback.current();\n }\n if (delay !== null) {\n let id = setTimeout(tick, delay);\n return () => clearTimeout(id);\n }\n }, [delay]);\n};",
"example": "const OneSecondTimer = props => {\n const [seconds, setSeconds] = React.useState(0);\n useTimeout(() => {\n setSeconds(seconds + 1);\n }, 1000);\n\n return <p>{seconds}</p>;\n};\n\nReactDOM.render(<OneSecondTimer />, document.getElementById('root'));"
},
"tags": [
"hooks",
"effect",
"intermediate"
]
},
"meta": {
"hash": "83e13b09dccd6fa310703dfa7cc61e446fc10f1757125f2a6ad86833a4772c82",
"firstSeen": "1566386637",
"lastUpdated": "1567858517",
"updateCount": 3
}
}
],
"meta": {
"specification": "http://jsonapi.org/format/",
"type": "snippetArray",
"language": {
"short": "jsx",
"long": "React"
},
"otherLanguages": [
{
"short": "css",
"long": "CSS"
}
]
}
}