Update snippet formatting

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-09-06 14:20:45 +03:00
parent f384fc0ee3
commit 95746a843b
18 changed files with 60 additions and 71 deletions

View File

@ -9,7 +9,7 @@ Renders a string as plaintext, with URLs converted to appropriate `<a>` elements
- 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. - 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.
```jsx ```jsx
function AutoLink({ text }) { const AutoLink = ({ text }) => {
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; 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;
return ( return (
@ -24,7 +24,7 @@ function AutoLink({ text }) {
})} })}
</React.Fragment> </React.Fragment>
); );
} };
``` ```
```jsx ```jsx

View File

@ -6,19 +6,19 @@ tags: components,state,effect,intermediate
Renders an `<input>` element with internal state, that uses a callback function to pass its value to the parent component. Renders an `<input>` element with internal state, that uses a callback function to pass its value to the parent component.
- Use object destructuring to set defaults for certain attributes of the `<input>` element. - Use object destructuring to set defaults for certain attributes of the `<input>` element.
- Use the `React.setState()` hook to create the `value` state variable and give it a value of equal to the `defaultValue` prop. - Use the `React.useState()` hook to create the `value` state variable and give it a value of equal to the `defaultValue` prop.
- 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. - 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.
- Render an `<input>` element with the appropriate attributes and use the the `onChange` event to upda the `value` state variable. - Render an `<input>` element with the appropriate attributes and use the the `onChange` event to upda the `value` state variable.
```jsx ```jsx
function ControlledInput({ const ControlledInput = ({
callback, callback,
type = 'text', type = 'text',
disabled = false, disabled = false,
readOnly = false, readOnly = false,
defaultValue, defaultValue,
placeholder = '' placeholder = ''
}) { }) => {
const [value, setValue] = React.useState(defaultValue); const [value, setValue] = React.useState(defaultValue);
React.useEffect(() => { React.useEffect(() => {
@ -35,7 +35,7 @@ function ControlledInput({
onChange={({ target: { value } }) => setValue(value)} onChange={({ target: { value } }) => setValue(value)}
/> />
); );
} };
``` ```
```jsx ```jsx

View File

@ -15,7 +15,7 @@ Renders a countdown timer that prints a message when it reaches zero.
- If `over` is `true`, the timer will display a message instead of the value of `time`. - If `over` is `true`, the timer will display a message instead of the value of `time`.
```jsx ```jsx
function CountDown({ hours = 0, minutes = 0, seconds = 0 }) { const CountDown = ({ hours = 0, minutes = 0, seconds = 0 }) => {
const [paused, setPaused] = React.useState(false); const [paused, setPaused] = React.useState(false);
const [over, setOver] = React.useState(false); const [over, setOver] = React.useState(false);
const [time, setTime] = React.useState({ const [time, setTime] = React.useState({
@ -27,24 +27,25 @@ function CountDown({ hours = 0, minutes = 0, seconds = 0 }) {
const tick = () => { const tick = () => {
if (paused || over) return; if (paused || over) return;
if (time.hours == 0 && time.minutes == 0 && time.seconds == 0) setOver(true); if (time.hours == 0 && time.minutes == 0 && time.seconds == 0) setOver(true);
else if (time.minutes == 0 && time.seconds == 0) else if (time.minutes == 0 && time.seconds == 0) {
setTime({ setTime({
hours: time.hours - 1, hours: time.hours - 1,
minutes: 59, minutes: 59,
seconds: 59 seconds: 59
}); });
else if (time.seconds == 0) } else if (time.seconds == 0) {
setTime({ setTime({
hours: time.hours, hours: time.hours,
minutes: time.minutes - 1, minutes: time.minutes - 1,
seconds: 59 seconds: 59
}); });
else } else {
setTime({ setTime({
hours: time.hours, hours: time.hours,
minutes: time.minutes, minutes: time.minutes,
seconds: time.seconds - 1 seconds: time.seconds - 1
}); });
}
}; };
const reset = () => { const reset = () => {
@ -72,7 +73,7 @@ function CountDown({ hours = 0, minutes = 0, seconds = 0 }) {
<button onClick={() => reset()}>Restart</button> <button onClick={() => reset()}>Restart</button>
</div> </div>
); );
} };
``` ```
```jsx ```jsx

View File

@ -10,10 +10,10 @@ Renders a list of elements from an array of primitives.
- Omit the `isOrdered` prop to render a `<ul>` list by default. - Omit the `isOrdered` prop to render a `<ul>` list by default.
```jsx ```jsx
function DataList({ isOrdered, data }) { const DataList = ({ isOrdered, data }) => {
const list = data.map((val, i) => <li key={`${i}_${val}`}>{val}</li>); const list = data.map((val, i) => <li key={`${i}_${val}`}>{val}</li>);
return isOrdered ? <ol>{list}</ol> : <ul>{list}</ul>; return isOrdered ? <ol>{list}</ol> : <ul>{list}</ul>;
} };
``` ```
```jsx ```jsx

View File

@ -9,7 +9,7 @@ Renders a table with rows dynamically created from an array of primitives.
- 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. - 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.
```jsx ```jsx
function DataTable({ data }) { const DataTable = ({ data }) => {
return ( return (
<table> <table>
<thead> <thead>
@ -28,7 +28,7 @@ function DataTable({ data }) {
</tbody> </tbody>
</table> </table>
); );
} };
``` ```
```jsx ```jsx

View File

@ -11,7 +11,7 @@ Renders a textarea component with a character limit.
- 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`. - 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`.
```jsx ```jsx
function LimitedTextarea({ rows, cols, value, limit }) { const LimitedTextarea = ({ rows, cols, value, limit }) => {
const [content, setContent] = React.useState(value); const [content, setContent] = React.useState(value);
const setFormattedContent = text => { const setFormattedContent = text => {
@ -35,7 +35,7 @@ function LimitedTextarea({ rows, cols, value, limit }) {
</p> </p>
</div> </div>
); );
} };
``` ```
```jsx ```jsx

View File

@ -12,7 +12,7 @@ Renders a textarea component with a word limit.
- 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`. - 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`.
```jsx ```jsx
function LimitedWordTextarea({ rows, cols, value, limit }) { const LimitedWordTextarea = ({ rows, cols, value, limit }) => {
const [content, setContent] = React.useState(value); const [content, setContent] = React.useState(value);
const [wordCount, setWordCount] = React.useState(0); const [wordCount, setWordCount] = React.useState(0);
@ -49,7 +49,7 @@ function LimitedWordTextarea({ rows, cols, value, limit }) {
</p> </p>
</div> </div>
); );
} };
``` ```
```jsx ```jsx

View File

@ -40,7 +40,7 @@ Creates a spinning loader component.
``` ```
```jsx ```jsx
function Loader({ size }) { const Loader = ({ size }) => {
return ( return (
<svg <svg
className="loader" className="loader"
@ -57,7 +57,7 @@ function Loader({ size }) {
<circle cx="12" cy="12" r="10" /> <circle cx="12" cy="12" r="10" />
</svg> </svg>
); );
} };
``` ```
```jsx ```jsx

View File

@ -7,13 +7,13 @@ Renders a table with rows dynamically created from an array of objects and a lis
- 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`. - 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`.
- Render a `<table>` element with a set of columns equal to the amount of values in `propertyNames`. - Render a `<table>` element with a set of columns equal to the amount of values in `propertyNames`.
- Use `Array.prototype.map` to render each value in the `propertyNames` array as a `<th>` element. - Use `Array.prototype.map()` to render each value in the `propertyNames` array as a `<th>` element.
- 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. - 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.
_This component does not work with nested objects and will break if there are nested objects inside any of the properties specified in `propertyNames`_ _This component does not work with nested objects and will break if there are nested objects inside any of the properties specified in `propertyNames`_
```jsx ```jsx
function MappedTable({ data, propertyNames }) { const MappedTable = ({ data, propertyNames }) => {
let filteredData = data.map(v => let filteredData = data.map(v =>
Object.keys(v) Object.keys(v)
.filter(k => propertyNames.includes(k)) .filter(k => propertyNames.includes(k))
@ -39,7 +39,7 @@ function MappedTable({ data, propertyNames }) {
</tbody> </tbody>
</table> </table>
); );
} };
``` ```
```jsx ```jsx

View File

@ -92,20 +92,20 @@ To use the component, import `Modal` only once and then display it by passing a
``` ```
```jsx ```jsx
function Modal({ isVisible = false, title, content, footer, onClose }) { const Modal = ({ isVisible = false, title, content, footer, onClose }) => {
React.useEffect(() => { React.useEffect(() => {
document.addEventListener('keydown', keydownHandler); document.addEventListener('keydown', keydownHandler);
return () => document.removeEventListener('keydown', keydownHandler); return () => document.removeEventListener('keydown', keydownHandler);
}); });
function keydownHandler({ key }) { const keydownHandler = ({ key }) => {
switch (key) { switch (key) {
case 'Escape': case 'Escape':
onClose(); onClose();
break; break;
default: default:
} }
} };
return !isVisible ? null : ( return !isVisible ? null : (
<div className="modal" onClick={onClose}> <div className="modal" onClick={onClose}>
@ -123,12 +123,11 @@ function Modal({ isVisible = false, title, content, footer, onClose }) {
</div> </div>
</div> </div>
); );
} };
``` ```
```jsx ```jsx
//Add the component to the render function const App = () => {
function App() {
const [isModal, setModal] = React.useState(false); const [isModal, setModal] = React.useState(false);
return ( return (
@ -143,7 +142,7 @@ function App() {
/> />
</React.Fragment> </React.Fragment>
); );
} };
ReactDOM.render(<App />, document.getElementById('root')); ReactDOM.render(<App />, document.getElementById('root'));
``` ```

View File

@ -5,7 +5,7 @@ tags: components,input,state,array,intermediate
Renders a checkbox list that uses a callback function to pass its selected value/values to the parent component. Renders a checkbox list that uses a callback function to pass its selected value/values to the parent component.
- Use `React.setState()` to create a `data` state variable and set its initial value equal to the `options` prop. - Use `React.useState()` to create a `data` state variable and set its initial value equal to the `options` prop.
- 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. - 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.
- 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. - 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.
- 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. - 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.
@ -22,7 +22,7 @@ const style = {
} }
}; };
function MultiselectCheckbox({ options, onChange }) { const MultiselectCheckbox = ({ options, onChange }) => {
const [data, setData] = React.useState(options); const [data, setData] = React.useState(options);
const toggle = item => { const toggle = item => {
@ -45,7 +45,7 @@ function MultiselectCheckbox({ options, onChange }) {
})} })}
</ul> </ul>
); );
} };
``` ```
```jsx ```jsx

View File

@ -9,7 +9,7 @@ Renders a password input field with a reveal button.
- Use a`<div>` to wrap both the`<input>` and the `<button>` element that toggles the type of the input field between `"text"` and `"password"`. - Use a`<div>` to wrap both the`<input>` and the `<button>` element that toggles the type of the input field between `"text"` and `"password"`.
```jsx ```jsx
function PasswordRevealer({ value }) { const PasswordRevealer = ({ value }) => {
const [shown, setShown] = React.useState(false); const [shown, setShown] = React.useState(false);
return ( return (
@ -18,7 +18,7 @@ function PasswordRevealer({ value }) {
<button onClick={() => setShown(!shown)}>Show/Hide</button> <button onClick={() => setShown(!shown)}>Show/Hide</button>
</div> </div>
); );
} };
``` ```
```jsx ```jsx

View File

@ -61,7 +61,7 @@ Renders a button that animates a ripple effect when clicked.
``` ```
```jsx ```jsx
function RippleButton({ children, onClick }) { const RippleButton = ({ children, onClick }) => {
const [coords, setCoords] = React.useState({ x: -1, y: -1 }); const [coords, setCoords] = React.useState({ x: -1, y: -1 });
const [isRippling, setIsRippling] = React.useState(false); const [isRippling, setIsRippling] = React.useState(false);
@ -102,12 +102,12 @@ function RippleButton({ children, onClick }) {
}} }}
/> />
) : ( ) : (
"" ''
)} )}
<span className="content">{children}</span> <span className="content">{children}</span>
</button> </button>
); );
} };
``` ```
```jsx ```jsx

View File

@ -11,7 +11,7 @@ Renders a `<select>` element that uses a callback function to pass its value to
- Use destructuring on the `values` array to pass an array of `value` and `text` elements. - Use destructuring on the `values` array to pass an array of `value` and `text` elements.
```jsx ```jsx
function Select({ values, callback, disabled = false, readonly = false, selected }) { const Select = ({ values, callback, disabled = false, readonly = false, selected }) => {
return ( return (
<select <select
disabled={disabled} disabled={disabled}
@ -26,22 +26,11 @@ function Select({ values, callback, disabled = false, readonly = false, selected
))} ))}
</select> </select>
); );
} };
let choices = [
['grapefruit', 'Grapefruit'],
['lime', 'Lime'],
['coconut', 'Coconut'],
['mango', 'Mango']
];
ReactDOM.render(
<Select values={choices} selected="lime" callback={val => console.log(val)} />,
document.getElementById('root')
);
``` ```
```jsx ```jsx
let choices = [ const choices = [
['grapefruit', 'Grapefruit'], ['grapefruit', 'Grapefruit'],
['lime', 'Lime'], ['lime', 'Lime'],
['coconut', 'Coconut'], ['coconut', 'Coconut'],

View File

@ -9,7 +9,7 @@ Renders a slider element that uses a callback function to pass its value to the
- 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. - 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.
```jsx ```jsx
function Slider({ callback, disabled = false, readOnly = false }) { const Slider = ({ callback, disabled = false, readOnly = false }) => {
return ( return (
<input <input
type="range" type="range"
@ -18,7 +18,7 @@ function Slider({ callback, disabled = false, readOnly = false }) {
onChange={({ target: { value } }) => callback(value)} onChange={({ target: { value } }) => callback(value)}
/> />
); );
} };
``` ```
```jsx ```jsx

View File

@ -9,14 +9,14 @@ Renders a `<textarea>` element that uses a callback function to pass its value t
- 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. - 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.
```jsx ```jsx
function TextArea({ const TextArea = ({
callback, callback,
cols = 20, cols = 20,
rows = 2, rows = 2,
disabled = false, disabled = false,
readOnly = false, readOnly = false,
placeholder = '' placeholder = ''
}) { }) => {
return ( return (
<textarea <textarea
cols={cols} cols={cols}
@ -27,7 +27,7 @@ function TextArea({
onChange={({ target: { value } }) => callback(value)} onChange={({ target: { value } }) => callback(value)}
/> />
); );
} };
``` ```
```jsx ```jsx

View File

@ -7,7 +7,7 @@ Renders a tree view of a JSON object or array with collapsible content.
- Use object destructuring to set defaults for certain props. - Use object destructuring to set defaults for certain props.
- Use the value of the `toggled` prop to determine the initial state of the content (collapsed/expanded). - Use the value of the `toggled` prop to determine the initial state of the content (collapsed/expanded).
- Use the `React.setState()` hook to create the `isToggled` state variable and give it the value of the `toggled` prop initially. - Use the `React.useState()` hook to create the `isToggled` state variable and give it the value of the `toggled` prop initially.
- Return a `<div>` to wrap the contents of the component and the `<span>` element, used to alter the component's `isToggled` state. - Return a `<div>` to wrap the contents of the component and the `<span>` element, used to alter the component's `isToggled` state.
- Determine the appearance of the component, based on `isParentToggled`, `isToggled`, `name` and `Array.isArray()` on `data`. - Determine the appearance of the component, based on `isParentToggled`, `isToggled`, `name` and `Array.isArray()` on `data`.
- For each child in `data`, determine if it is an object or array and recursively render a sub-tree. - For each child in `data`, determine if it is an object or array and recursively render a sub-tree.
@ -50,14 +50,14 @@ div.tree-element:before {
``` ```
```jsx ```jsx
function TreeView({ const TreeView = ({
data, data,
toggled = true, toggled = true,
name = null, name = null,
isLast = true, isLast = true,
isChildElement = false, isChildElement = false,
isParentToggled = true isParentToggled = true
}) { }) => {
const [isToggled, setIsToggled] = React.useState(toggled); const [isToggled, setIsToggled] = React.useState(toggled);
return ( return (
@ -96,11 +96,11 @@ function TreeView({
{!isLast ? ',' : ''} {!isLast ? ',' : ''}
</div> </div>
); );
} };
``` ```
```jsx ```jsx
let data = { const data = {
lorem: { lorem: {
ipsum: 'dolor sit', ipsum: 'dolor sit',
amet: { amet: {

View File

@ -9,13 +9,13 @@ Renders an `<input>` element that uses a callback function to pass its value to
- 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. - 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.
```jsx ```jsx
function UncontrolledInput({ const UncontrolledInput = ({
callback, callback,
type = 'text', type = 'text',
disabled = false, disabled = false,
readOnly = false, readOnly = false,
placeholder = '' placeholder = ''
}) { }) => {
return ( return (
<input <input
type={type} type={type}
@ -25,7 +25,7 @@ function UncontrolledInput({
onChange={({ target: { value } }) => callback(value)} onChange={({ target: { value } }) => callback(value)}
/> />
); );
} };
``` ```
```jsx ```jsx