379 lines
42 KiB
JSON
379 lines
42 KiB
JSON
[
|
|
{
|
|
"name": "Accordion.md",
|
|
"title": "Accordion",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.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);\n```"
|
|
],
|
|
"expertise": 2,
|
|
"tags": [
|
|
"visual",
|
|
"children",
|
|
"state"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "AutoLink.md",
|
|
"title": "AutoLink",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(\n <AutoLink text=\"foo bar baz http://example.org bar\" />,\n document.getElementById('root')\n);\n```"
|
|
],
|
|
"expertise": 2,
|
|
"tags": [
|
|
"string",
|
|
"fragment",
|
|
"regexp"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "Carousel.md",
|
|
"title": "Carousel",
|
|
"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.setEffect()` 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": [
|
|
"```jsx\nfunction 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 });\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}\n```",
|
|
"```jsx\nReactDOM.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);\n```"
|
|
],
|
|
"expertise": 2,
|
|
"tags": [
|
|
"visual",
|
|
"children",
|
|
"state",
|
|
"effect"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "Collapse.md",
|
|
"title": "Collapse",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(\n <Collapse>\n <h1>This is a collapse</h1>\n <p>Hello world!</p>\n </Collapse>,\n document.getElementById('root')\n);\n```"
|
|
],
|
|
"expertise": 2,
|
|
"tags": [
|
|
"visual",
|
|
"children",
|
|
"state"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "CountDown.md",
|
|
"title": "CountDown",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(<CountDown hours=\"1\" minutes=\"45\" />, document.getElementById('root'));\n```"
|
|
],
|
|
"expertise": 2,
|
|
"tags": [
|
|
"visual",
|
|
"state"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "DataList.md",
|
|
"title": "DataList",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nconst names = ['John', 'Paul', 'Mary'];\nReactDOM.render(<DataList data={names} />, document.getElementById('root'));\nReactDOM.render(<DataList data={names} isOrdered />, document.getElementById('root'));\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"array"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "DataTable.md",
|
|
"title": "DataTable",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nconst people = ['John', 'Jesse'];\nReactDOM.render(<DataTable data={people} />, document.getElementById('root'));\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"array"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "FileDrop.md",
|
|
"title": "FileDrop",
|
|
"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.\nThe 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": [
|
|
"```css\n.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}\n```",
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(<FileDrop handleDrop={console.log} />, document.getElementById('root'));\n```"
|
|
],
|
|
"expertise": 2,
|
|
"tags": [
|
|
"visual",
|
|
"input",
|
|
"state",
|
|
"effect"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "Input.md",
|
|
"title": "Input",
|
|
"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": [
|
|
"```jsx\nfunction Input({ callback, type = 'text', disabled = false, readOnly = false, placeholder = '' }) {\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}\n```",
|
|
"```jsx\nReactDOM.render(\n <Input type=\"text\" placeholder=\"Insert some text here...\" callback={val => console.log(val)} />,\n document.getElementById('root')\n);\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"input"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "LimitedTextarea.md",
|
|
"title": "LimitedTextarea",
|
|
"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`.\nCreate 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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(<LimitedTextarea limit={32} value=\"Hello!\" />, document.getElementById('root'));\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"input",
|
|
"state",
|
|
"effect"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "LimitedWordTextarea.md",
|
|
"title": "LimitedWordTextarea",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(\n <LimitedWordTextArea limit={5} value=\"Hello there!\" />,\n document.getElementById('root')\n);\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"input",
|
|
"state",
|
|
"effect"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "Mailto.md",
|
|
"title": "Mailto",
|
|
"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": [
|
|
"```jsx\nfunction Mailto({ email, subject, body, ...props }) {\n return (\n <a href={`mailto:${email}?subject=${subject || ''}&body=${body || ''}`}>{props.children}</a>\n );\n}\n```",
|
|
"```jsx\nReactDOM.render(\n <Mailto email=\"foo@bar.baz\" subject=\"Hello\" body=\"Hello world!\">\n Mail me!\n </Mailto>,\n document.getElementById('root')\n);\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"visual"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "MappedTable.md",
|
|
"title": "MappedTable",
|
|
"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",
|
|
"codeBlocks": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nconst 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);\n```"
|
|
],
|
|
"expertise": 1,
|
|
"tags": [
|
|
"array",
|
|
"object"
|
|
],
|
|
"notes": [
|
|
"This component does not work with nested objects and will break if there are nested objects inside any of the properties specified in `propertyNames`.",
|
|
"<!-tags: array,object -->",
|
|
"<!-expertise: 1 -->"
|
|
]
|
|
},
|
|
{
|
|
"name": "MultiselectCheckbox.md",
|
|
"title": "MultiselectCheckbox",
|
|
"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": [
|
|
"```jsx\nconst 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.map((_, 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}\n```",
|
|
"```jsx\nconst 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);\n```"
|
|
],
|
|
"expertise": 1,
|
|
"tags": [
|
|
"input",
|
|
"state",
|
|
"array"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "PasswordRevealer.md",
|
|
"title": "PasswordRevealer",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(<PasswordRevealer />, document.getElementById('root'));\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"input",
|
|
"state"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "Select.md",
|
|
"title": "Select",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nlet 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);\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"input"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "Slider.md",
|
|
"title": "Slider",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(<Slider callback={val => console.log(val)} />, document.getElementById('root'));\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"input"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "StarRating.md",
|
|
"title": "StarRating",
|
|
"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.setState()` 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": [
|
|
"```jsx\nfunction 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={() => setRating(event.target.getAttribute('star-id') || this.state.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}\n```",
|
|
"```jsx\nReactDOM.render(<StarRating />, document.getElementById('root'));\nReactDOM.render(<StarRating rating={2} />, document.getElementById('root'));\n```"
|
|
],
|
|
"expertise": 2,
|
|
"tags": [
|
|
"visual",
|
|
"children",
|
|
"input",
|
|
"state"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "Tabs.md",
|
|
"title": "Tabs",
|
|
"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": [
|
|
"```css\n.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}\n```",
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.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);\n```"
|
|
],
|
|
"expertise": 1,
|
|
"tags": [
|
|
"visual",
|
|
"state",
|
|
"children"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "TextArea.md",
|
|
"title": "TextArea",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(\n <TextArea placeholder=\"Insert some text here...\" callback={val => console.log(val)} />,\n document.getElementById('root')\n);\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"input"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "Ticker.md",
|
|
"title": "Ticker",
|
|
"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": [
|
|
"```jsx\nfunction 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 }}>{this.state.ticker}</span>\n <button onClick={this.tick}>Tick!</button>\n <button onClick={this.reset}>Reset</button>\n </div>\n );\n}\n```",
|
|
"```jsx\nReactDOM.render(<Ticker times={5} interval={1000} />, document.getElementById('root'));\n```"
|
|
],
|
|
"expertise": 1,
|
|
"tags": [
|
|
"visual",
|
|
"state"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "Toggle.md",
|
|
"title": "Toggle",
|
|
"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": [
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(<Toggle />, document.getElementById('root'));\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"visual",
|
|
"state"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "Tooltip.md",
|
|
"title": "Tooltip",
|
|
"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": [
|
|
"```css\n.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}\n```",
|
|
"```jsx\nfunction 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}\n```",
|
|
"```jsx\nReactDOM.render(\n <Tooltip text=\"Simple tooltip\">\n <button>Hover me!</button>\n </Tooltip>,\n document.getElementById('root')\n);\n```"
|
|
],
|
|
"expertise": 1,
|
|
"tags": [
|
|
"visual",
|
|
"state",
|
|
"children"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "TreeView.md",
|
|
"title": "TreeView",
|
|
"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": [
|
|
"```css\n.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}\n```",
|
|
"```jsx\nfunction 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> {name}: </strong> : <span> </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}\n```",
|
|
"```jsx\nlet 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'));\n```"
|
|
],
|
|
"expertise": 2,
|
|
"tags": [
|
|
"object",
|
|
"visual",
|
|
"state",
|
|
"recursion"
|
|
],
|
|
"notes": []
|
|
}
|
|
] |