Update snippet descriptions

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-11-16 16:50:57 +02:00
parent 1c622b64d7
commit 9d9032fda7
5 changed files with 95 additions and 112 deletions

View File

@ -1,29 +1,27 @@
---
title: LimitedTextarea
tags: components,state,effect,event,beginner
tags: components,state,callback,event,beginner
---
Renders a textarea component with a character limit.
- Use the `React.useState()` hook to create the `content` state variable and set its value to `value`.
Create a method `setFormattedContent`, which trims the content of the input if it's longer than `limit`.
- Use the `React.useEffect()` hook to call the `setFormattedContent` method on the value of the `content` state variable.
- 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 the `useState()` hook to create the `content` state variable and set its value to that of `value` prop, trimmed down to `limit` characters.
- Create a method `setFormattedContent`, which trims the content down to `limit` characters and memoize it, using the `useCallback()` hook.
- Bind the `onChange` event of the `<textarea>` to call `setFormattedContent` with the value of the fired event.
```jsx
const LimitedTextarea = ({ rows, cols, value, limit }) => {
const [content, setContent] = React.useState(value);
const [content, setContent] = React.useState(value.slice(0, limit));
const setFormattedContent = text => {
text.length > limit ? setContent(text.slice(0, limit)) : setContent(text);
};
React.useEffect(() => {
setFormattedContent(content);
}, []);
const setFormattedContent = React.useCallback(
text => {
setContent(text.slice(0, limit));
},
[limit, setContent]
);
return (
<div>
<>
<textarea
rows={rows}
cols={cols}
@ -33,11 +31,14 @@ const LimitedTextarea = ({ rows, cols, value, limit }) => {
<p>
{content.length}/{limit}
</p>
</div>
</>
);
};
```
```jsx
ReactDOM.render(<LimitedTextarea limit={32} value="Hello!" />, document.getElementById('root'));
ReactDOM.render(
<LimitedTextarea limit={32} value="Hello!" />,
document.getElementById('root')
);
```

View File

@ -1,43 +1,44 @@
---
title: LimitedWordTextarea
tags: components,input,state,effect,event,beginner
tags: components,input,state,callback,effect,event,intermediate
---
Renders a textarea component with a word limit.
- Use the `React.useState()` hook to create the `content` and `wordCount` state variables and set their values to `value` and `0` respectively.
- 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`.
- If the afforementioned `length` exceeds the `limit`, trim the input, otherwise return the raw input, updating `content` and `wordCount` accordingly in both cases.
- Use the `React.useEffect()` hook to call the `setFormattedContent` method on the value of the `content` state variable.
- 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 the `useState()` hook to create a state variable, containing `content` and `wordCount`, using the `value` prop and `0` as the initial values respectively.
- Use the `useCallback()` hooks to create a memoized function, `setFormattedContent`, that uses `String.prototype.split()` to turn the input into an array of words.
- Check if the result of applying `Array.prototype.filter()` combined with `Boolean` has a `length` longer than `limit` and, if so, trim the input, otherwise return the raw input, updating state accordingly in both cases.
- Use the `useEffect()` hook to call the `setFormattedContent` method on the value of the `content` state variable during the inital render.
- Bind the `onChange` event of the `<textarea>` to call `setFormattedContent` with the value of `event.target.value`.
```jsx
const LimitedWordTextarea = ({ rows, cols, value, limit }) => {
const [content, setContent] = React.useState(value);
const [wordCount, setWordCount] = React.useState(0);
const [{ content, wordCount }, setContent] = React.useState({
content: value,
wordCount: 0
});
const setFormattedContent = text => {
let words = text.split(' ');
if (words.filter(Boolean).length > limit) {
setContent(
text
.split(' ')
.slice(0, limit)
.join(' ')
);
setWordCount(limit);
} else {
setContent(text);
setWordCount(words.filter(Boolean).length);
}
};
const setFormattedContent = React.useCallback(
text => {
let words = text.split(' ').filter(Boolean);
if (words.length > limit) {
setContent({
content: words.slice(0, limit).join(' '),
wordCount: limit
});
} else {
setContent({ content: text, wordCount: words.length });
}
},
[limit, setContent]
);
React.useEffect(() => {
setFormattedContent(content);
}, []);
return (
<div>
<>
<textarea
rows={rows}
cols={cols}
@ -47,7 +48,7 @@ const LimitedWordTextarea = ({ rows, cols, value, limit }) => {
<p>
{wordCount}/{limit}
</p>
</div>
</>
);
};
```

View File

@ -1,42 +0,0 @@
---
title: Ticker
tags: components,state,beginner
---
Renders a ticker component.
- Use the `React.useState()` hook to initialize the `ticker` state variable to `0`.
- Define two methods, `tick` and `reset`, that will periodically increment `timer` based on `intervalId` and reset `intervalId` respectively.
- Return a `<div>` with two `<button>` elements, each of which calls `tick` and `reset` respectively.
```jsx
const Ticker = ({ times, interval }) => {
const [ticker, setTicker] = React.useState(0);
let intervalId = null;
const tick = () => {
reset();
intervalId = setInterval(() => {
if (ticker < times) setTicker(ticker + 1);
else clearInterval(intervalId);
}, interval);
};
const reset = () => {
setTicker(0);
clearInterval(intervalId);
};
return (
<div>
<span style={{ fontSize: 100 }}>{ticker}</span>
<button onClick={tick}>Tick!</button>
<button onClick={reset}>Reset</button>
</div>
);
};
```
```jsx
ReactDOM.render(<Ticker times={5} interval={1000} />, document.getElementById('root'));
```

View File

@ -5,28 +5,39 @@ tags: components,state,beginner
Renders a toggle component.
- Use the `React.useState()` to initialize the `isToggleOn` state variable to `defaultToggled`.
- Use an object, `style`, to hold the styles for individual components and their states.
- 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.
- Use the `useState()` hook to initialize the `isToggleOn` state variable to `defaultToggled`.
- Render an `<input>` and bind its `onClick` event to update the `isToggledOn` state variable, applying the appropriate `className` to the wrapping `<label>`.
```css
.toggle input[type="checkbox"] {
display: none;
}
.toggle.on {
background-color: green;
}
.toggle.off {
background-color: red;
}
```
```jsx
const Toggle = ({ defaultToggled = false }) => {
const [isToggleOn, setIsToggleOn] = React.useState(defaultToggled);
const style = {
on: {
backgroundColor: 'green'
},
off: {
backgroundColor: 'grey'
}
};
return (
<button onClick={() => setIsToggleOn(!isToggleOn)} style={isToggleOn ? style.on : style.off}>
<label className={isToggleOn ? 'toggle on' : 'toggle off'}>
<input
type="checkbox"
checked={isToggleOn}
onChange={() => setIsToggleOn(!isToggleOn)}
/>
{isToggleOn ? 'ON' : 'OFF'}
</button>
</label>
);
};
```
```jsx

View File

@ -5,20 +5,22 @@ tags: components,object,state,recursion,advanced
Renders a tree view of a JSON object or array with collapsible content.
- 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 `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.
- 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.
- Otherwise, render a `<p>` element with the appropriate style.
- Use the `useState()` hook to create the `isToggled` state variable and give it the value of the `toggled` prop initially.
- Render a `<span>` element and bind its `onClick` event to alter the component's `isToggled` state.
- Determine the appearance of the component, based on `isParentToggled`, `isToggled`, `name` and checking for `Array.isArray()` on `data`.
- For each child in `data`, determine if it is an object or array and recursively render a sub-tree or a text element with the appropriate style.
```css
.tree-element {
margin: 0;
margin: 0 0 0 4px;
position: relative;
}
.tree-element.is-child {
margin-left: 16px;
}
div.tree-element:before {
content: '';
position: absolute;
@ -28,6 +30,10 @@ div.tree-element:before {
border-left: 1px solid gray;
}
p.tree-element {
margin-left: 16px;
}
.toggler {
position: absolute;
top: 10px;
@ -59,40 +65,43 @@ const TreeView = ({
isParentToggled = true
}) => {
const [isToggled, setIsToggled] = React.useState(toggled);
const isDataArray = Array.isArray(data);
return (
<div
style={{ marginLeft: isChildElement ? 16 : 4 + 'px' }}
className={isParentToggled ? 'tree-element' : 'tree-element collapsed'}
className={`tree-element ${isParentToggled && 'collapsed'} ${
isChildElement && 'is-child'
}`}
>
<span
className={isToggled ? 'toggler' : 'toggler closed'}
onClick={() => setIsToggled(!isToggled)}
/>
{name ? <strong>&nbsp;&nbsp;{name}: </strong> : <span>&nbsp;&nbsp;</span>}
{Array.isArray(data) ? '[' : '{'}
{isDataArray ? '[' : '{'}
{!isToggled && '...'}
{Object.keys(data).map((v, i, a) =>
typeof data[v] == 'object' ? (
typeof data[v] === 'object' ? (
<TreeView
key={`${name}-${v}-${i}`}
data={data[v]}
isLast={i === a.length - 1}
name={Array.isArray(data) ? null : v}
name={isDataArray ? null : v}
isChildElement
isParentToggled={isParentToggled && isToggled}
/>
) : (
<p
style={{ marginLeft: 16 + 'px' }}
key={`${name}-${v}-${i}`}
className={isToggled ? 'tree-element' : 'tree-element collapsed'}
>
{Array.isArray(data) ? '' : <strong>{v}: </strong>}
{isDataArray ? '' : <strong>{v}: </strong>}
{data[v]}
{i === a.length - 1 ? '' : ','}
</p>
)
)}
{Array.isArray(data) ? ']' : '}'}
{isDataArray ? ']' : '}'}
{!isLast ? ',' : ''}
</div>
);
@ -122,5 +131,8 @@ const data = {
ipsum: 'primis'
}
};
ReactDOM.render(<TreeView data={data} name="data" />, document.getElementById('root'));
ReactDOM.render(
<TreeView data={data} name="data" />,
document.getElementById('root')
);
```