318 lines
34 KiB
JSON
318 lines
34 KiB
JSON
[
|
|
{
|
|
"name": "AutoLink.md",
|
|
"title": "AutoLink",
|
|
"text": "Renders a string as plaintext, with URLs converted to appropriate `<a>` elements.\n\nUse `String.prototype.split()` and `String.prototype.match()` with a regular expression to find URLs in a string.\nReturn 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 (\n <a href={url.startsWith(\"http\") ? url : `http://${url}`}>{url}</a>\n );\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\nUse the `React.setState()` hook to create the `active` state variable and give it a value of `0` (index of the first item).\nUse an object, `style`, to hold the styles for the individual components.\nUse the `React.setEffect()` hook to update the value of `active` to the index of the next item, using `setTimeout`.\nDestructure `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.\nRender 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\nUse the `React.setState()` hook to create the `isCollapsed` state variable with an initial value of `props.collapsed`.\nUse an object, `style`, to hold the styles for individual components and their states.\nUse 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`.\nDetermine the appearance of the content, based on `isCollapsed` and apply the appropriate CSS rules from the `style` object.\nFinally, 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\n style={style.buttonStyle}\n onClick={() => setIsCollapsed(!isCollapsed)}\n >\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": "DataList.md",
|
|
"title": "DataList",
|
|
"text": "Renders a list of elements from an array of primitives.\n\nUse the value of the `isOrdered` prop to conditionally render a `<ol>` or `<ul>` list.\nUse `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.\nOmit 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) => (\n <li key={`${i}_${val}`}>{val}</li>\n ));\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\nRender a `<table>` element with two columns (`ID` and `Value`).\nUse `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(\n <DataTable data={people} />,\n document.getElementById('root')\n);\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"array"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "FileDrop.md",
|
|
"title": "FileDrop",
|
|
"text": "Renders a file drag and drop component for a single file.\n\nCreate a ref called `dropRef` for this component.\nUse 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\nCreate the `handleDrag`, `handleDragIn`, `handleDragOut` and `handleDrop` methods to handle drag and drop functionality, bind them to the component's context.\nEach 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`.\nReturn an appropriately styled `<div>` and use `drag` and `filename` to determine its contents and style. \nFinally, bind the `ref` of the created `<div>` to `dropRef`.\n\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={\n drag ? \"filedrop drag\" : filename ? \"filedrop ready\" : \"filedrop\"\n }\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\nUse object destructuring to set defaults for certain attributes of the `<input>` element.\nRender 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\nUse 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`.\nUse the `React.useEffect()` hook to call the `setFormattedContent` method on the value of the `content` state variable.\nUse 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(\n <LimitedTextarea limit={32} value='Hello!' />,\n document.getElementById('root')\n);\n```"
|
|
],
|
|
"expertise": 0,
|
|
"tags": [
|
|
"input",
|
|
"state",
|
|
"effect"
|
|
],
|
|
"notes": []
|
|
},
|
|
{
|
|
"name": "LimitedWordTextarea.md",
|
|
"title": "LimitedWordTextarea",
|
|
"text": "Renders a textarea component with a word limit.\n\nUse the `React.useState()` hook to create the `content` and `wordCount` state variables and set their values to `value` and `0` respectively.\nCreate 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`.\nIf the afforementioned `length` exceeds the `limit`, trim the input, otherwise return the raw input, updating `content` and `wordCount` accordingly in both cases.\nUse the `React.useEffect()` hook to call the `setFormattedContent` method on the value of the `content` state variable.\nUse 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\nDestructure the component's props, use `email`, `subject` and `body` to create a `<a>` element with an appropriate `href` attribute.\nRender 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 || \"\"}`}>\n {props.children}\n </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\nUse `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`.\nRender a `<table>` element with a set of columns equal to the amount of values in `propertyNames`.\nUse `Array.prototype.map` to render each value in the `propertyNames` array as a `<th>` element.\nUse `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>{propertyNames.map(val => <th key={`h_${val}`}>{val}</th>)}</tr>\n </thead>\n <tbody>\n {filteredData.map((val, i) => (\n <tr key={`i_${i}`}>\n {propertyNames.map(p => <td key={`i_${i}_${p}`}>{val[p]}</td>)}\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": "PasswordRevealer.md",
|
|
"title": "PasswordRevealer",
|
|
"text": "Renders a password input field with a reveal button.\n\nUse the `React.useState()` hook to create the `shown` state variable and set its value to `false`.\nUse 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\n type={shown ? \"text\" : \"password\"}\n value={value}\n onChange={() => {}}\n />\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\nUse object destructuring to set defaults for certain attributes of the `<select>` element.\nRender 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.\nUse 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]) => <option selected={selected === value}value={value}>{text}</option>)}\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": "StarRating.md",
|
|
"title": "StarRating",
|
|
"text": "Renders a star rating component.\n\nDefine a component, called `Star` that will render each individual star with the appropriate appearance, based on the parent component's state.\nIn 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`.\nCreate a method, `hoverOver`, that updates `selected` and `rating` according to the provided `event`.\nCreate 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. \nFinally, 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(\n typeof props.rating == \"number\" ? props.rating : 0\n );\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={() =>\n setRating(event.target.getAttribute(\"star-id\") || this.state.rating)\n }\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": "Tab",
|
|
"text": "Renders a tabbed menu and view component.\n\nDefine a `TabItem` component, pass it to the `Tab` and remove unnecessary nodes expect for `TabItem` by identifying the function's name in `props.children`.\nUse the `React.useState()` hook to initialize the value of the `bindIndex` state variable to `props.defaultIndex`. \nUse `Array.prototype.map` on the collected nodes to render the `tab-menu` and `tab-view`. \nDefine `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\n onClick={() => changeTab(index)}\n className={bindIndex === index ? \"focus\" : \"\"}\n >\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\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\nUse object destructuring to set defaults for certain attributes of the `<textarea>` element.\nRender 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 ({ callback, cols = 20, rows = 2, disabled = false, readOnly = false, placeholder='' }) {\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\nUse the `React.useState()` hook to initialize the `ticker` state variable to `0`.\nDefine two methods, `tick` and `reset`, that will periodically increment `timer` based on `interval` and reset `interval` respectively.\nReturn 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) \n setTicker(ticker + 1);\n else \n 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\nUse the `React.useState()` to initialize the `isToggleOn` state variable to `false`.\nUse an object, `style`, to hold the styles for individual components and their states.\nReturn 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\n onClick={() => setIsToggleOn(!isToggleOn)}\n style={isToggleOn ? style.on : style.off}\n >\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\nUse the `React.useState()` hook to create the `show` variable and initialize it to `false`.\nReturn a `<div>` element that contains the `<div>` that will be the tooltip and the `children` passed to the component.\nHandle 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\n {...rest}\n onMouseEnter={() => setShow(true)}\n onMouseLeave={() => setShow(false)}\n >\n {children}\n </div>\n </div>\n );\n}\n```",
|
|
"```jsx\n ReactDOM.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\nUse object destructuring to set defaults for certain props. \nUse the value of the `toggled` prop to determine the initial state of the content (collapsed/expanded).\nUse the `React.setState()` hook to create the `isToggled` state variable and give it the value of the `toggled` prop initially.\nReturn a `<div>` to wrap the contents of the component and the `<span>` element, used to alter the component's `isToggled` state.\nDetermine the appearance of the component, based on `isParentToggled`, `isToggled`, `name` and `Array.isArray()` on `data`. \nFor each child in `data`, determine if it is an object or array and recursively render a sub-tree.\nOtherwise, 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(\n (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": []
|
|
}
|
|
] |