Update fork to match original repo
Update fork to match original repo
This commit is contained in:
@ -33,6 +33,6 @@ ReactDOM.render(
|
||||
);
|
||||
```
|
||||
|
||||
<!-- tags: string,fragment,functional -->
|
||||
<!-- tags: string,fragment,regexp -->
|
||||
|
||||
<!-- expertise: 2 -->
|
||||
|
||||
@ -2,70 +2,49 @@
|
||||
|
||||
Renders a carousel component.
|
||||
|
||||
Initially set `state.active` to `0` (index of the first item).
|
||||
Use the `React.setState()` hook to create the `active` state variable and give it a value of `0` (index of the first item).
|
||||
Use an object, `style`, to hold the styles for the individual components.
|
||||
Define a method, `setActiveItem`, which uses `this.setState` to change the state's `active` property to the index of the next item.
|
||||
Define another method, `changeItem`, which is called by `setActiveItem` after updating the state each time and also when the component
|
||||
first renders (on `ComponentDidMount`).
|
||||
In the `render()` method, destructure `state`, `style` and `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.
|
||||
Render the carousel items using [React.cloneElement](https://reactjs.org/docs/react-api.html#cloneelement) and pass down rest
|
||||
`props` along with the computed styles.
|
||||
Use the `React.setEffect()` hook to update the value of `active` to the index of the next item, using `setTimeout`.
|
||||
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.
|
||||
Render the carousel items using `React.cloneElement()` and pass down rest `props` along with the computed styles.
|
||||
|
||||
```jsx
|
||||
class Carousel extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
active: 0
|
||||
};
|
||||
this.scrollInterval = null;
|
||||
this.style = {
|
||||
carousel: {
|
||||
position: "relative"
|
||||
},
|
||||
carouselItem: {
|
||||
position: "absolute",
|
||||
visibility: "hidden"
|
||||
},
|
||||
visible: {
|
||||
visibility: "visible"
|
||||
}
|
||||
};
|
||||
}
|
||||
componentDidMount() {
|
||||
this.changeItem();
|
||||
}
|
||||
setActiveItem = () => {
|
||||
const { carouselItems } = this.props;
|
||||
this.setState(
|
||||
prevState => ({
|
||||
active: (prevState.active + 1) % carouselItems.length
|
||||
}),
|
||||
this.changeItem
|
||||
);
|
||||
function Carousel(props) {
|
||||
const [active, setActive] = React.useState(0);
|
||||
let scrollInterval = null;
|
||||
const style = {
|
||||
carousel: {
|
||||
position: "relative"
|
||||
},
|
||||
carouselItem: {
|
||||
position: "absolute",
|
||||
visibility: "hidden"
|
||||
},
|
||||
visible: {
|
||||
visibility: "visible"
|
||||
}
|
||||
};
|
||||
changeItem = () => {
|
||||
this.scrollInterval = setTimeout(this.setActiveItem, 2000);
|
||||
};
|
||||
render() {
|
||||
const { carouselItems, ...rest } = this.props;
|
||||
const { active } = this.state;
|
||||
const { visible, carousel, carouselItem } = this.style;
|
||||
return (
|
||||
<div style={carousel}>
|
||||
{carouselItems.map((item, index) => {
|
||||
const activeStyle = active === index ? visible : {};
|
||||
return React.cloneElement(item, {
|
||||
...rest,
|
||||
style: {
|
||||
...carouselItem,
|
||||
...activeStyle
|
||||
}
|
||||
});
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
React.useEffect(() => {
|
||||
scrollInterval = setTimeout(() => {
|
||||
const { carouselItems } = props;
|
||||
setActive((active + 1) % carouselItems.length);
|
||||
}, 2000);
|
||||
});
|
||||
const { carouselItems, ...rest } = props;
|
||||
return (
|
||||
<div style={style.carousel}>
|
||||
{carouselItems.map((item, index) => {
|
||||
const activeStyle = active === index ? style.visible : {};
|
||||
return React.cloneElement(item, {
|
||||
...rest,
|
||||
style: {
|
||||
...style.carouselItem,
|
||||
...activeStyle
|
||||
}
|
||||
});
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@ -82,7 +61,7 @@ ReactDOM.render(
|
||||
);
|
||||
```
|
||||
|
||||
<!-- tags: visual,children,state,class -->
|
||||
<!-- tags: visual,children,state,effect -->
|
||||
|
||||
<!-- expertise: 2 -->
|
||||
|
||||
|
||||
@ -2,55 +2,46 @@
|
||||
|
||||
Renders a component with collapsible content.
|
||||
|
||||
Use the value of the `collapsed` prop to determine the initial state of the content (collapsed/expanded).
|
||||
Set the `state` of the component to the value of the `collapsed` prop (cast to a boolean value) and bind the `toggleCollapse` method to the component's context.
|
||||
Use the `React.setState()` hook to create the `isCollapsed` state variable with an initial value of `props.collapsed`.
|
||||
Use an object, `style`, to hold the styles for individual components and their states.
|
||||
Create a method, `toggleCollapse`, which uses `Component.prototype.setState` to change the component's `state` from collapsed to expanded and vice versa.
|
||||
In the `render()` method, use a `<div>` to wrap both the `<button>` that alters the component's `state` and the content of the component, passed down via `props.children`.
|
||||
Determine the appearance of the content, based on `state.collapsed` and apply the appropriate CSS rules from the `style` object.
|
||||
Finally, update the value of the `aria-expanded` attribute based on `state.collapsed` to make the component accessible.
|
||||
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`.
|
||||
Determine the appearance of the content, based on `isCollapsed` and apply the appropriate CSS rules from the `style` object.
|
||||
Finally, update the value of the `aria-expanded` attribute based on `isCollapsed` to make the component accessible.
|
||||
|
||||
```jsx
|
||||
class Collapse extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
collapsed: !!props.collapsed
|
||||
};
|
||||
this.style = {
|
||||
collapsed: {
|
||||
display: 'none'
|
||||
},
|
||||
expanded: {
|
||||
display: 'block'
|
||||
},
|
||||
buttonStyle: {
|
||||
display: 'block',
|
||||
width: '100%'
|
||||
}
|
||||
};
|
||||
this.toggleCollapse = this.toggleCollapse.bind(this);
|
||||
}
|
||||
|
||||
toggleCollapse() {
|
||||
this.setState(state => ({ collapsed: !state.collapsed }));
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<button style={this.style.buttonStyle} onClick={this.toggleCollapse}>
|
||||
{this.state.collapsed ? 'Show' : 'Hide'} content
|
||||
</button>
|
||||
<div
|
||||
style= {this.state.collapsed ? this.style.collapsed : this.style.expanded}
|
||||
aria-expanded = {this.state.collapsed}
|
||||
>
|
||||
{this.props.children}
|
||||
</div>
|
||||
function Collapse(props) {
|
||||
const [isCollapsed, setIsCollapsed] = React.useState(props.collapsed);
|
||||
|
||||
const style = {
|
||||
collapsed: {
|
||||
display: "none"
|
||||
},
|
||||
expanded: {
|
||||
display: "block"
|
||||
},
|
||||
buttonStyle: {
|
||||
display: "block",
|
||||
width: "100%"
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button
|
||||
style={style.buttonStyle}
|
||||
onClick={() => setIsCollapsed(!isCollapsed)}
|
||||
>
|
||||
{isCollapsed ? "Show" : "Hide"} content
|
||||
</button>
|
||||
<div
|
||||
className="collapse-content"
|
||||
style={isCollapsed ? style.collapsed : style.expanded}
|
||||
aria-expanded={isCollapsed}
|
||||
>
|
||||
{props.children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@ -64,6 +55,6 @@ ReactDOM.render(
|
||||
);
|
||||
```
|
||||
|
||||
<!-- tags: visual,children,state,class -->
|
||||
<!-- tags: visual,children,state -->
|
||||
|
||||
<!-- expertise: 2 -->
|
||||
|
||||
@ -21,6 +21,6 @@ ReactDOM.render(<DataList data={names}/>, document.getElementById('root'));
|
||||
ReactDOM.render(<DataList data={names} isOrdered/>, document.getElementById('root'));
|
||||
```
|
||||
|
||||
<!-- tags: array,functional -->
|
||||
<!-- tags: array -->
|
||||
|
||||
<!-- expertise: 0 -->
|
||||
|
||||
@ -36,6 +36,6 @@ ReactDOM.render(
|
||||
);
|
||||
```
|
||||
|
||||
<!-- tags: array,functional -->
|
||||
<!-- tags: array -->
|
||||
|
||||
<!-- expertise: 0 -->
|
||||
|
||||
@ -3,12 +3,13 @@
|
||||
Renders a file drag and drop component for a single file.
|
||||
|
||||
Create a ref called `dropRef` for this component.
|
||||
Initialize `state.drag` and `state.filename` to `false` and `''` respectively.
|
||||
The variables `dragCounter` and `state.drag` are used to determine if a file is being dragged, while `state.filename` is used to store the dropped file's name.
|
||||
Use the `React.useState()` hook to create the `drag` and `filename` variables, initialized to `false` and `''` respectively.
|
||||
The variables `dragCounter` and `drag` are used to determine if a file is being dragged, while `filename` is used to store the dropped file's name.
|
||||
|
||||
Create the `handleDrag`, `handleDragIn`, `handleDragOut` and `handleDrop` methods to handle drag and drop functionality, bind them to the component's context.
|
||||
Each of the methods will handle a specific event, the listeners for which are created and removed in `componentDidMount` and `componentWillUnmount` respectively.
|
||||
`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 `this.props.handleDrop`.
|
||||
In the `render()` method, create an appropriately styled `<div>` and use `state.drag` and `state.filename` to determine its contents and style.
|
||||
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.
|
||||
`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`.
|
||||
Return an appropriately styled `<div>` and use `drag` and `filename` to determine its contents and style.
|
||||
Finally, bind the `ref` of the created `<div>` to `dropRef`.
|
||||
|
||||
|
||||
@ -32,79 +33,67 @@ Finally, bind the `ref` of the created `<div>` to `dropRef`.
|
||||
```
|
||||
|
||||
```jsx
|
||||
class FileDrop extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.dropRef = React.createRef();
|
||||
this.state = {
|
||||
drag: false,
|
||||
filename: ''
|
||||
}
|
||||
this.handleDrag = this.handleDrag.bind(this);
|
||||
this.handleDragIn = this.handleDragIn.bind(this);
|
||||
this.handleDragOut = this.handleDragOut.bind(this);
|
||||
this.handleDrop = this.handleDrop.bind(this);
|
||||
}
|
||||
function FileDrop(props) {
|
||||
const [drag, setDrag] = React.useState(false);
|
||||
const [filename, setFilename] = React.useState('');
|
||||
let dropRef = React.createRef();
|
||||
let dragCounter = 0;
|
||||
|
||||
handleDrag(e) {
|
||||
const handleDrag = e => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
};
|
||||
|
||||
handleDragIn(e) {
|
||||
const handleDragIn = e => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.dragCounter++;
|
||||
if (e.dataTransfer.items && e.dataTransfer.items.length > 0)
|
||||
this.setState({ drag: true });
|
||||
}
|
||||
dragCounter++;
|
||||
if (e.dataTransfer.items && e.dataTransfer.items.length > 0) setDrag(true);
|
||||
};
|
||||
|
||||
handleDragOut(e) {
|
||||
const handleDragOut = e => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.dragCounter--;
|
||||
if (this.dragCounter === 0)
|
||||
this.setState({ drag: false });
|
||||
}
|
||||
dragCounter--;
|
||||
if (dragCounter === 0) setDrag(false);
|
||||
};
|
||||
|
||||
handleDrop(e) {
|
||||
const handleDrop = e => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.setState({ drag: false });
|
||||
setDrag(false);
|
||||
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
||||
this.props.handleDrop(e.dataTransfer.files[0]);
|
||||
this.setState({ filename : e.dataTransfer.files[0].name});
|
||||
props.handleDrop(e.dataTransfer.files[0]);
|
||||
setFilename(e.dataTransfer.files[0].name);
|
||||
e.dataTransfer.clearData();
|
||||
this.dragCounter = 0;
|
||||
dragCounter = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
componentDidMount() {
|
||||
let div = this.dropRef.current;
|
||||
div.addEventListener('dragenter', this.handleDragIn);
|
||||
div.addEventListener('dragleave', this.handleDragOut);
|
||||
div.addEventListener('dragover', this.handleDrag);
|
||||
div.addEventListener('drop', this.handleDrop);
|
||||
}
|
||||
React.useEffect(() => {
|
||||
let div = dropRef.current;
|
||||
div.addEventListener("dragenter", handleDragIn);
|
||||
div.addEventListener("dragleave", handleDragOut);
|
||||
div.addEventListener("dragover", handleDrag);
|
||||
div.addEventListener("drop", handleDrop);
|
||||
return function cleanup() {
|
||||
div.removeEventListener("dragenter", handleDragIn);
|
||||
div.removeEventListener("dragleave", handleDragOut);
|
||||
div.removeEventListener("dragover", handleDrag);
|
||||
div.removeEventListener("drop", handleDrop);
|
||||
};
|
||||
});
|
||||
|
||||
componentWillUnmount() {
|
||||
let div = this.dropRef.current;
|
||||
div.removeEventListener('dragenter', this.handleDragIn);
|
||||
div.removeEventListener('dragleave', this.handleDragOut);
|
||||
div.removeEventListener('dragover', this.handleDrag);
|
||||
div.removeEventListener('drop', this.handleDrop);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div ref={this.dropRef} className={this.state.drag ? 'filedrop drag' : this.state.filename ? 'filedrop ready' : 'filedrop'}>
|
||||
{this.state.filename && !this.state.drag ?
|
||||
<div>{this.state.filename}</div>
|
||||
: <div>Drop files here!</div>
|
||||
}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div
|
||||
ref={dropRef}
|
||||
className={
|
||||
drag ? "filedrop drag" : filename ? "filedrop ready" : "filedrop"
|
||||
}
|
||||
>
|
||||
{filename && !drag ? <div>{filename}</div> : <div>Drop files here!</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@ -112,6 +101,6 @@ class FileDrop extends React.Component {
|
||||
ReactDOM.render(<FileDrop handleDrop={console.log}/>, document.getElementById('root'));
|
||||
```
|
||||
|
||||
<!-- tags: visual,input,state,class -->
|
||||
<!-- tags: visual,input,state,effect -->
|
||||
|
||||
<!-- expertise: 2 -->
|
||||
|
||||
@ -26,6 +26,6 @@ ReactDOM.render(
|
||||
);
|
||||
```
|
||||
|
||||
<!-- tags: input,functional -->
|
||||
<!-- tags: input -->
|
||||
|
||||
<!-- expertise: 0 -->
|
||||
|
||||
@ -2,41 +2,36 @@
|
||||
|
||||
Renders a textarea component with a character limit.
|
||||
|
||||
Use the value of the `value` prop to determine the initial `state.content` and `state.characterCount` and the value of the `limit` props to determine the value of `state.limit`.
|
||||
Create a method, `handleChange`, which trims the `event.target.value` data if necessary and uses `Component.prototype.setState` to update `state.content` and `state.characterCount`, and bind it to the component's context.
|
||||
In the`render()` method, 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 the `handleChange` method.
|
||||
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`.
|
||||
|
||||
```jsx
|
||||
class LimitedTextarea extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
content: props.value,
|
||||
characterCount: props.value.length,
|
||||
limit: props.limit
|
||||
};
|
||||
this.handleChange = this.handleChange.bind(this);
|
||||
}
|
||||
|
||||
handleChange(event) {
|
||||
let newContent = event.target.value;
|
||||
if(newContent.length >= this.state.limit) newContent = newContent.slice(0, this.state.limit);
|
||||
this.setState(state => ({ content: newContent, characterCount: newContent.length }));
|
||||
}
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<textarea
|
||||
rows={this.props.rows}
|
||||
cols={this.props.cols}
|
||||
onChange={this.handleChange}
|
||||
value={this.state.content}
|
||||
>
|
||||
</textarea>
|
||||
<p>{this.state.characterCount}/{this.props.limit}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function LimitedTextarea({ rows, cols, value, limit }) {
|
||||
const [content, setContent] = React.useState(value);
|
||||
|
||||
const setFormattedContent = text => {
|
||||
text.length > limit ? setContent(text.slice(0, limit)) : setContent(text);
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
setFormattedContent(content);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<textarea
|
||||
rows={rows}
|
||||
cols={cols}
|
||||
onChange={event => setFormattedContent(event.target.value)}
|
||||
value={content}
|
||||
/>
|
||||
<p>
|
||||
{content.length}/{limit}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@ -46,8 +41,7 @@ ReactDOM.render(
|
||||
document.getElementById('root')
|
||||
);
|
||||
```
|
||||
|
||||
<!-- tags: input,state,class -->
|
||||
<!-- tags: input,state,effect -->
|
||||
|
||||
<!-- expertise: 0 -->
|
||||
|
||||
|
||||
61
snippets/LimitedWordTextarea.md
Normal file
61
snippets/LimitedWordTextarea.md
Normal file
@ -0,0 +1,61 @@
|
||||
### LimitedWordTextarea
|
||||
|
||||
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`.
|
||||
|
||||
```jsx
|
||||
function LimitedWordTextarea({ rows, cols, value, limit }) {
|
||||
const [content, setContent] = React.useState(value);
|
||||
const [wordCount, setWordCount] = React.useState(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);
|
||||
}
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
setFormattedContent(content);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<textarea
|
||||
rows={rows}
|
||||
cols={cols}
|
||||
onChange={event => setFormattedContent(event.target.value)}
|
||||
value={content}
|
||||
/>
|
||||
<p>
|
||||
{wordCount}/{limit}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```jsx
|
||||
ReactDOM.render(
|
||||
<LimitedWordTextArea limit={5} value='Hello there!' />,
|
||||
document.getElementById('root')
|
||||
);
|
||||
```
|
||||
<!-- tags: input,state,effect -->
|
||||
|
||||
<!-- expertise: 0 -->
|
||||
|
||||
@ -24,6 +24,6 @@ ReactDOM.render(
|
||||
);
|
||||
```
|
||||
|
||||
<!-- tags: visual,functional -->
|
||||
<!-- tags: visual -->
|
||||
|
||||
<!-- expertise: 0 -->
|
||||
|
||||
@ -46,6 +46,6 @@ ReactDOM.render(
|
||||
#### 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,functional -->
|
||||
<!-- tags: array,object -->
|
||||
|
||||
<!-- expertise: 1 -->
|
||||
|
||||
@ -1,141 +0,0 @@
|
||||
### ModalDialog
|
||||
|
||||
Renders a dialog component in a modal, controllable through events.
|
||||
To use the component, import `ModalDialog` only once and then display it using `ModalDialog.show()`, passing the JSX templates and data as parameters.
|
||||
|
||||
Define `modalHandler`, a method that will handle showing the modal dialog, set `state` to the default values initially and bind the `close` and `modalClick` methods to the component's context.
|
||||
Define `close` and `modalClick` to toggle the visibility of the modal dialog, based on `state.closeOnClick`.
|
||||
Use the CustomEvent API to listen for `modal` events, that can be dispatched from the `static` `show()` method, handle listeners appropriately from `componentDidMount` and `componentWillUnmount`.
|
||||
|
||||
The `show()` method accepts an argument, that should contain three parameters:
|
||||
* `title`, a string for the dialog's title
|
||||
* `closeOnClick`, `true` if the modal should close on click or `false` if it should only close when clicking the *X* button
|
||||
* `content`, which is the JSX content to be rendered inside the dialog
|
||||
|
||||
Finally, in the `render()` method, use a `<div>` to wrap everything and render the modal dialog with the content passed to `show()`.
|
||||
|
||||
```css
|
||||
.modal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.6);
|
||||
z-index: 9998;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
.dialog {
|
||||
background-color: white;
|
||||
border-radius: 5px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.dialog-title {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 48px;
|
||||
padding: 0 16px;
|
||||
border-bottom: 0.5px solid #c3c3c3;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
.dialog-close {
|
||||
font-size: 32px;
|
||||
color: #c3c3c3;
|
||||
cursor: pointer;
|
||||
transform: rotate(45deg);
|
||||
user-select: none;
|
||||
}
|
||||
.dialog-close:hover {
|
||||
color: red;
|
||||
}
|
||||
.dialog-content {
|
||||
min-width: 300px;
|
||||
}
|
||||
```
|
||||
|
||||
```jsx
|
||||
class ModalDialog extends React.Component {
|
||||
constructor() {
|
||||
super();
|
||||
this.modalHandler = (e) => {
|
||||
this.setState({
|
||||
data: e.detail.data,
|
||||
visible: true
|
||||
});
|
||||
};
|
||||
this.state = {
|
||||
data: {
|
||||
title: '',
|
||||
closeOnClick: false,
|
||||
content: ''
|
||||
},
|
||||
visible: false
|
||||
};
|
||||
this.close = this.close.bind(this);
|
||||
this.modalClick = this.modalClick.bind(this);
|
||||
}
|
||||
render() {
|
||||
return !this.state.visible ? null : <div className="modal" onClick={this.modalClick}>
|
||||
<div className="dialog">
|
||||
<div className="dialog-title">{ this.state.data.title }<span className="dialog-close" onClick={this.close}>+</span></div>
|
||||
<div className="dialog-content">
|
||||
{
|
||||
this.state.data.content
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
componentDidMount() {
|
||||
document.addEventListener('modal', this.modalHandler);
|
||||
}
|
||||
componentWillUnmount() {
|
||||
document.removeEventListener('modal', this.modalHandler);
|
||||
}
|
||||
close() {
|
||||
this.setState({
|
||||
visible: false,
|
||||
data: {
|
||||
title: '',
|
||||
closeOnClick: false,
|
||||
content: ''
|
||||
}
|
||||
});
|
||||
}
|
||||
static show(data) {
|
||||
document.dispatchEvent(new CustomEvent('modal', {
|
||||
detail: {
|
||||
data
|
||||
}
|
||||
}));
|
||||
}
|
||||
modalClick() {
|
||||
if (this.state.data.closeOnClick) this.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```jsx
|
||||
// add to render function
|
||||
<ModalDialog />
|
||||
|
||||
// every time you wanna call the dialog
|
||||
// content is a jsx element
|
||||
ModalDialog.show({
|
||||
title: 'Hello, world!',
|
||||
closeOnClick: true,
|
||||
content: <img src="https://github.com/30-seconds/30-seconds-of-react/blob/master/logo.png"/>
|
||||
});
|
||||
```
|
||||
|
||||
#### Notes:
|
||||
* This component includes a lot of CSS, which might conflict with other CSS in your project. It is recomended for the modal to be a direct child of the body tag.
|
||||
* A more up-to-date method with lower compatibility is to use [Portals](https://reactjs.org/docs/portals.html) in React 16+.
|
||||
|
||||
<!-- tags: visual,static,children,state,class -->
|
||||
|
||||
<!-- expertise: 1 -->
|
||||
@ -2,36 +2,23 @@
|
||||
|
||||
Renders a password input field with a reveal button.
|
||||
|
||||
Initially set `state.shown` to `false` to ensure that the password is not shown by default.
|
||||
Create a method, `toggleShown`, which uses `Component.prototype.setState` to change the input's state from shown to hidden and vice versa, bind it to the component's context.
|
||||
In the`render()` method, use a`<div>` to wrap both the`<input>` and the `<button>` element that toggles the type of the input field.
|
||||
Finally, bind the `<button>`'s `onClick` event to the `toggleShown` method.
|
||||
Use the `React.useState()` hook to create the `shown` state variable and set its value to `false`.
|
||||
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
|
||||
class PasswordRevealer extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
shown: false
|
||||
};
|
||||
this.toggleShown = this.toggleShown.bind(this);
|
||||
}
|
||||
function PasswordRevealer({ value }) {
|
||||
const [shown, setShown] = React.useState(false);
|
||||
|
||||
toggleShown() {
|
||||
this.setState(state => ({ shown: !state.shown }));
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<input
|
||||
type={this.state.shown ? 'text' : 'password'}
|
||||
value={this.props.value}
|
||||
/>
|
||||
<button onClick={this.toggleShown}>Show/Hide</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<input
|
||||
type={shown ? "text" : "password"}
|
||||
value={value}
|
||||
onChange={() => {}}
|
||||
/>
|
||||
<button onClick={() => setShown(!shown)}>Show/Hide</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@ -39,7 +26,7 @@ class PasswordRevealer extends React.Component {
|
||||
ReactDOM.render(<PasswordRevealer />, document.getElementById('root'));
|
||||
```
|
||||
|
||||
<!--tags: input,state,class -->
|
||||
<!--tags: input,state -->
|
||||
|
||||
<!--expertise: 0 -->
|
||||
|
||||
|
||||
@ -33,6 +33,6 @@ ReactDOM.render(
|
||||
);
|
||||
```
|
||||
|
||||
<!-- tags: input,functional -->
|
||||
<!-- tags: input -->
|
||||
|
||||
<!-- expertise: 0 -->
|
||||
|
||||
@ -2,68 +2,50 @@
|
||||
|
||||
Renders a star rating component.
|
||||
|
||||
Use and IIFE to define a functional component, called `Star` that will render each individual star with the appropriate appearance, based on the parent component's `state` and return the class component `StarRating`.
|
||||
Use the value of the `rating` prop to determine if a valid rating is supplied and store it in `state.rating` (or `0` if invalid or not supplied).
|
||||
Initialize `state.selection` to `0`.
|
||||
Create two methods, `hoverOver` and `setRating`, that take an event as argument and update `state.selected` and `state.rating` according to it, bind them both to the component's context.
|
||||
In the `render()` method, 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 `state.selection` to `0`, the `onClick` event to set
|
||||
the `state.rating` and the `onMouseOver` event to set `state.selection` to the `star-id` attribute of the `event.target` respectively.
|
||||
Define a component, called `Star` that will render each individual star with the appropriate appearance, based on the parent component's state.
|
||||
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`.
|
||||
Create a method, `hoverOver`, that updates `selected` and `rating` according to the provided `event`.
|
||||
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.
|
||||
Finally, pass the appropriate values to each `<Star>` component (`starId` and `marked`).
|
||||
|
||||
```jsx
|
||||
const StarRating = (function() {
|
||||
function Star({ marked, starId }) {
|
||||
return (
|
||||
<span star-id={starId} style={{ color: '#ff9933' }} role='button'>
|
||||
{marked ? '\u2605' : '\u2606'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
function Star({ marked, starId }) {
|
||||
return (
|
||||
<span star-id={starId} style={{ color: "#ff9933" }} role="button">
|
||||
{marked ? "\u2605" : "\u2606"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return class StarRating extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
rating: typeof props.rating == 'number' ? props.rating : 0,
|
||||
selection: 0
|
||||
};
|
||||
this.hoverOver = this.hoverOver.bind(this);
|
||||
this.hoverOut = this.hoverOver.bind(this, null);
|
||||
this.handleClick = this.handleClick.bind(this);
|
||||
}
|
||||
hoverOver(event) {
|
||||
let val = 0;
|
||||
if (event && event.target && event.target.getAttribute('star-id'))
|
||||
val = event.target.getAttribute('star-id');
|
||||
this.setState(state => ({ selection: val }));
|
||||
}
|
||||
handleClick(event) {
|
||||
const val = event.target.getAttribute('star-id') || this.state.rating;
|
||||
this.setState(state => ({ rating: val }));
|
||||
}
|
||||
render() {
|
||||
return (
|
||||
<div
|
||||
onMouseOut={this.hoverOut}
|
||||
onClick={this.handleClick}
|
||||
onMouseOver={this.hoverOver}
|
||||
>
|
||||
{Array.from({ length: 5 }, (v, i) => (
|
||||
<Star
|
||||
starId={i+1}
|
||||
key={`star_${i+1} `}
|
||||
marked={
|
||||
this.state.selection
|
||||
? this.state.selection >= i+1
|
||||
: this.state.rating >= i+1
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function StarRating(props) {
|
||||
const [rating, setRating] = React.useState(
|
||||
typeof props.rating == "number" ? props.rating : 0
|
||||
);
|
||||
const [selection, setSelection] = React.useState(0);
|
||||
const hoverOver = event => {
|
||||
let val = 0;
|
||||
if (event && event.target && event.target.getAttribute("star-id"))
|
||||
val = event.target.getAttribute("star-id");
|
||||
setSelection(val);
|
||||
};
|
||||
})();
|
||||
return (
|
||||
<div
|
||||
onMouseOut={() => hoverOver(null)}
|
||||
onClick={() =>
|
||||
setRating(event.target.getAttribute("star-id") || this.state.rating)
|
||||
}
|
||||
onMouseOver={hoverOver}
|
||||
>
|
||||
{Array.from({ length: 5 }, (v, i) => (
|
||||
<Star
|
||||
starId={i + 1}
|
||||
key={`star_${i + 1} `}
|
||||
marked={selection ? selection >= i + 1 : rating >= i + 1}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```jsx
|
||||
@ -71,6 +53,6 @@ ReactDOM.render(<StarRating/>, document.getElementById('root'));
|
||||
ReactDOM.render(<StarRating rating={2} />, document.getElementById('root'));
|
||||
```
|
||||
|
||||
<!-- tags: visual,children,input,state,class -->
|
||||
<!-- tags: visual,children,input,state -->
|
||||
|
||||
<!-- expertise: 2 -->
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
### Tab
|
||||
Renders a tabbed menu and view component.
|
||||
|
||||
Define `TabItem` as a middleware, pass it to the `Tab` and remove unnecessary nodes expect for `TabItem` by identifying the function's name in `props.children`.
|
||||
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`.
|
||||
Use the `React.useState()` hook to initialize the value of the `bindIndex` state variable to `props.defaultIndex`.
|
||||
Use `Array.prototype.map` on the collected nodes to render the `tab-menu` and `tab-view`.
|
||||
Define `changeTab`, which will be executed when clicking a `<button>` from the `tab-menu`.
|
||||
`changeTab` executes the passed callback, `onTabClick` and updates `state.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`.
|
||||
`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`.
|
||||
|
||||
```css
|
||||
.tab-menu > button {
|
||||
@ -23,77 +24,59 @@ Define `changeTab`, which will be executed when clicking a `<button>` from the `
|
||||
```
|
||||
|
||||
```jsx
|
||||
class Tab extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
bindIndex: props.defaultIndex
|
||||
};
|
||||
}
|
||||
changeTab(newIndex) {
|
||||
if (typeof this.props.onTabClick === "function")
|
||||
this.props.onTabClick(newIndex);
|
||||
this.setState({
|
||||
bindIndex: newIndex
|
||||
});
|
||||
}
|
||||
buttonClass(index) {
|
||||
return this.state.bindIndex === index ? "focus" : "";
|
||||
}
|
||||
itemStyle(index) {
|
||||
return {
|
||||
display: this.state.bindIndex === index ? "block" : "none"
|
||||
};
|
||||
}
|
||||
render() {
|
||||
const items = this.props.children.filter(
|
||||
item => item.type.name === "TabItem"
|
||||
);
|
||||
return (
|
||||
<div className="wrapper">
|
||||
<div className="tab-menu">
|
||||
{items.map(({ props: { index, label } }) => (
|
||||
<button
|
||||
onClick={() => this.changeTab(index)}
|
||||
className={this.buttonClass(index)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="tab-view">
|
||||
{items.map(({ props }) => (
|
||||
<div
|
||||
{...props}
|
||||
className="tab-view_item"
|
||||
key={props.index}
|
||||
style={this.itemStyle(props.index)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
function TabItem(props) {
|
||||
return <div {...props} />;
|
||||
}
|
||||
|
||||
function Tabs(props) {
|
||||
const [bindIndex, setBindIndex] = React.useState(props.defaultIndex);
|
||||
const changeTab = newIndex => {
|
||||
if (typeof props.onTabClick === "function") props.onTabClick(newIndex);
|
||||
setBindIndex(newIndex);
|
||||
};
|
||||
const items = props.children.filter(item => item.type.name === "TabItem");
|
||||
|
||||
return (
|
||||
<div className="wrapper">
|
||||
<div className="tab-menu">
|
||||
{items.map(({ props: { index, label } }) => (
|
||||
<button
|
||||
onClick={() => changeTab(index)}
|
||||
className={bindIndex === index ? "focus" : ""}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="tab-view">
|
||||
{items.map(({ props }) => (
|
||||
<div
|
||||
{...props}
|
||||
className="tab-view_item"
|
||||
key={props.index}
|
||||
style={{ display: bindIndex === props.index ? "block" : "none" }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
```jsx
|
||||
ReactDOM.render(
|
||||
<Tab defaultIndex="1" onTabClick={console.log}>
|
||||
<Tabs defaultIndex="1" onTabClick={console.log}>
|
||||
<TabItem label="A" index="1">
|
||||
Lorem ipsum
|
||||
</TabItem>
|
||||
<TabItem label="B" index="2">
|
||||
Dolor sit amet
|
||||
</TabItem>
|
||||
</Tab>,
|
||||
</Tabs>,
|
||||
document.getElementById("root")
|
||||
);
|
||||
|
||||
```
|
||||
|
||||
<!-- tags: visual,children,class -->
|
||||
<!-- tags: visual,state,children -->
|
||||
|
||||
<!-- expertise: 1 -->
|
||||
|
||||
@ -27,6 +27,6 @@ ReactDOM.render(
|
||||
);
|
||||
```
|
||||
|
||||
<!-- tags: input,functional -->
|
||||
<!-- tags: input -->
|
||||
|
||||
<!-- expertise: 0 -->
|
||||
|
||||
@ -2,45 +2,37 @@
|
||||
|
||||
Renders a ticker component.
|
||||
|
||||
- The ticker state is initially set to zero
|
||||
- When the `Tick!` button is clicked, `timer` is incremented periodically at the given `interval`
|
||||
- When the `Reset` button is clicked, the value of the timer is set to zero and the `setInterval` is cleared
|
||||
- The `setInterval` is cleared once the desired `time` is reached
|
||||
- `time` and `interval` are the required props
|
||||
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 `interval` and reset `interval` respectively.
|
||||
Return a `<div>` with two `<button>` elements, each of which calls `tick` and `reset` respectively.
|
||||
|
||||
```jsx
|
||||
class Ticker extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {ticker: 0}
|
||||
this.interval = null
|
||||
}
|
||||
function Ticker(props) {
|
||||
const [ticker, setTicker] = React.useState(0);
|
||||
let interval = null;
|
||||
|
||||
tick = () => {
|
||||
this.reset()
|
||||
this.interval = setInterval(() => {
|
||||
if (this.state.ticker < this.props.times) {
|
||||
this.setState(({ ticker }) => ({ticker: ticker + 1}))
|
||||
}else{
|
||||
clearInterval(this.interval)
|
||||
}
|
||||
}, this.props.interval)
|
||||
}
|
||||
const tick = () => {
|
||||
reset();
|
||||
interval = setInterval(() => {
|
||||
if (ticker < props.times)
|
||||
setTicker(ticker + 1);
|
||||
else
|
||||
clearInterval(interval);
|
||||
}, props.interval);
|
||||
}
|
||||
|
||||
reset = () => {
|
||||
this.setState({ticker: 0})
|
||||
clearInterval(this.interval)
|
||||
}
|
||||
const reset = () => {
|
||||
setTicker(0);
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div>
|
||||
<span style={{fontSize: 100}}>{this.state.ticker}</span>
|
||||
<button onClick={this.tick}>Tick!</button>
|
||||
<button onClick={this.reset}>Reset</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<span style={{ fontSize: 100 }}>{this.state.ticker}</span>
|
||||
<button onClick={this.tick}>Tick!</button>
|
||||
<button onClick={this.reset}>Reset</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@ -48,6 +40,6 @@ class Ticker extends Component {
|
||||
ReactDOM.render(<Ticker times={5} interval={1000} />, document.getElementById('root'));
|
||||
```
|
||||
|
||||
<!-- tags: visual,state,class -->
|
||||
<!-- tags: visual,state -->
|
||||
|
||||
<!-- expertise: 1 -->
|
||||
@ -2,49 +2,30 @@
|
||||
|
||||
Renders a toggle component.
|
||||
|
||||
Initialize `state.isToggleOn` to `false`, bind the `handleClick` method to the component's context.
|
||||
Use the `React.useState()` to initialize the `isToggleOn` state variable to `false`.
|
||||
Use an object, `style`, to hold the styles for individual components and their states.
|
||||
Create a method, `handleClick`, which uses `Component.prototype.setState` to change the component's `state.toggleOn`.
|
||||
In the `render()` method, destructure `state` and `style`, create a `<button>` that alters the component's `state` and determine the appearance of the content based on `state.isToggleOn`, applying the appropriate CSS rules from the `style` object.
|
||||
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.
|
||||
|
||||
```jsx
|
||||
class Toggle extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
isToggleOn: false
|
||||
};
|
||||
this.style = {
|
||||
on: {
|
||||
backgroundColor: 'green'
|
||||
},
|
||||
off: {
|
||||
backgroundColor: 'grey'
|
||||
}
|
||||
};
|
||||
function Toggle(props) {
|
||||
const [isToggleOn, setIsToggleOn] = React.useState(false);
|
||||
style = {
|
||||
on: {
|
||||
backgroundColor: "green"
|
||||
},
|
||||
off: {
|
||||
backgroundColor: "grey"
|
||||
}
|
||||
};
|
||||
|
||||
this.handleClick = this.handleClick.bind(this);
|
||||
}
|
||||
|
||||
handleClick() {
|
||||
this.setState(state => ({
|
||||
isToggleOn: !state.isToggleOn
|
||||
}));
|
||||
}
|
||||
|
||||
render() {
|
||||
const { isToggleOn } = this.state;
|
||||
const { on, off } = this.style;
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={this.handleClick}
|
||||
style={isToggleOn ? on : off}
|
||||
>
|
||||
{isToggleOn ? 'ON' : 'OFF'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<button
|
||||
onClick={() => setIsToggleOn(!isToggleOn)}
|
||||
style={isToggleOn ? style.on : style.off}
|
||||
>
|
||||
{isToggleOn ? "ON" : "OFF"}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@ -52,6 +33,6 @@ class Toggle extends React.Component {
|
||||
ReactDOM.render(<Toggle />, document.getElementById('root'));
|
||||
```
|
||||
|
||||
<!-- tags: visual,state,class -->
|
||||
<!-- tags: visual,state -->
|
||||
|
||||
<!-- expertise: 0 -->
|
||||
|
||||
@ -2,67 +2,47 @@
|
||||
|
||||
Renders a tooltip component.
|
||||
|
||||
Set the `state` of the component to `show: false` initially, define an object, `style`, to hold the styles for individual components and their states.
|
||||
Create a method, `toggleTooltip`, which uses `this.setState` to change the state's `show` property from `true` to `false` and vice versa.
|
||||
Bind `showTooltip` and `hideTooltip` to the component's context with the respective values of `true` and `false`.
|
||||
In the `render()` method, compute if the tooltip should be shown or hidden, render the content of the tooltip and bind the `onMouseEnter` and `onMouseLeave` events to `showTooltip` and `hideTooltip` respectively.
|
||||
Use the `React.useState()` hook to create the `show` variable and initialize it to `false`.
|
||||
Return a `<div>` element that contains the `<div>` that will be the tooltip and the `children` passed to the component.
|
||||
Handle the `onMouseEnter` and `onMouseLeave` methods, by altering the value of the `show` variable.
|
||||
|
||||
```css
|
||||
.tooltip {
|
||||
position: relative;
|
||||
background: rgba(0, 0, 0, 0.7);
|
||||
color: white;
|
||||
visibility: hidden;
|
||||
padding: 5px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.tooltip-arrow {
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 50%;
|
||||
border-width: 5px;
|
||||
border-style: solid;
|
||||
border-color: rgba(0, 0, 0, 0.7) transparent transparent;
|
||||
}
|
||||
```
|
||||
```jsx
|
||||
class Tooltip extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
show: false
|
||||
};
|
||||
this.style = {
|
||||
tooltip: {
|
||||
position: 'relative',
|
||||
backgroundColor: "rgba(0,0,0,0.7)",
|
||||
color: "white",
|
||||
visibility: "hidden",
|
||||
width: "fit-content",
|
||||
padding: 5,
|
||||
borderRadius: 5
|
||||
},
|
||||
tooltipArrow: {
|
||||
position: 'absolute',
|
||||
top: '100%',
|
||||
left: '50%',
|
||||
borderWidth: 5,
|
||||
borderStyle: 'solid',
|
||||
borderColor: "rgba(0,0,0,0.7) transparent transparent",
|
||||
},
|
||||
visible: {
|
||||
visibility: "visible"
|
||||
},
|
||||
};
|
||||
this.showTooltip = this.toggleTooltip.bind(this, true);
|
||||
this.hideTooltip = this.toggleTooltip.bind(this, false);
|
||||
}
|
||||
function Tooltip({ children, text, ...rest }) {
|
||||
const [show, setShow] = React.useState(false);
|
||||
|
||||
toggleTooltip = tooltipState => {
|
||||
this.setState({
|
||||
show: tooltipState
|
||||
});
|
||||
};
|
||||
|
||||
render() {
|
||||
const { children, text, ...rest } = this.props;
|
||||
const { show } = this.state;
|
||||
const { visible, tooltip, tooltipArrow } = this.style;
|
||||
const showTooltip = show ? visible : {};
|
||||
return (
|
||||
<div>
|
||||
<div style={{ ...tooltip, ...showTooltip }}>
|
||||
{text}
|
||||
<span style={tooltipArrow}/>
|
||||
</div>
|
||||
<div {...rest} onMouseEnter={this.showTooltip} onMouseLeave={this.hideTooltip}>
|
||||
{children}
|
||||
</div>
|
||||
return (
|
||||
<div>
|
||||
<div className="tooltip" style={show ? { visibility: "visible" } : {}}>
|
||||
{text}
|
||||
<span className="tooltip-arrow" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
<div
|
||||
{...rest}
|
||||
onMouseEnter={() => setShow(true)}
|
||||
onMouseLeave={() => setShow(false)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@ -75,6 +55,6 @@ class Tooltip extends React.Component {
|
||||
);
|
||||
```
|
||||
|
||||
<!-- tags: visual,state,children,class -->
|
||||
<!-- tags: visual,state,children -->
|
||||
|
||||
<!-- expertise: 1 -->
|
||||
|
||||
128
snippets/TreeView.md
Normal file
128
snippets/TreeView.md
Normal file
@ -0,0 +1,128 @@
|
||||
### TreeView
|
||||
|
||||
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.setState()` 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.
|
||||
|
||||
```css
|
||||
.tree-element {
|
||||
margin: 0;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
div.tree-element:before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 24px;
|
||||
left: 1px;
|
||||
height: calc(100% - 48px);
|
||||
border-left: 1px solid gray;
|
||||
}
|
||||
|
||||
.toggler {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
left: 0px;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-top: 4px solid transparent;
|
||||
border-bottom: 4px solid transparent;
|
||||
border-left: 5px solid gray;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.toggler.closed {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.collapsed {
|
||||
display: none;
|
||||
}
|
||||
```
|
||||
|
||||
```jsx
|
||||
function TreeView({
|
||||
data,
|
||||
toggled = true,
|
||||
name = null,
|
||||
isLast = true,
|
||||
isChildElement = false,
|
||||
isParentToggled = true
|
||||
}) {
|
||||
const [isToggled, setIsToggled] = React.useState(toggled);
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{ marginLeft: isChildElement ? 16 : 4 + "px" }}
|
||||
className={isParentToggled ? "tree-element" : "tree-element collapsed"}
|
||||
>
|
||||
<span
|
||||
className={isToggled ? "toggler" : "toggler closed"}
|
||||
onClick={() => setIsToggled(!isToggled)}
|
||||
/>
|
||||
{name ? <strong> {name}: </strong> : <span> </span>}
|
||||
{Array.isArray(data) ? "[" : "{"}
|
||||
{!isToggled && "..."}
|
||||
{Object.keys(data).map(
|
||||
(v, i, a) =>
|
||||
typeof data[v] == "object" ? (
|
||||
<TreeView
|
||||
data={data[v]}
|
||||
isLast={i === a.length - 1}
|
||||
name={Array.isArray(data) ? null : v}
|
||||
isChildElement
|
||||
isParentToggled={isParentToggled && isToggled}
|
||||
/>
|
||||
) : (
|
||||
<p
|
||||
style={{ marginLeft: 16 + "px" }}
|
||||
className={isToggled ? "tree-element" : "tree-element collapsed"}
|
||||
>
|
||||
{Array.isArray(data) ? "" : <strong>{v}: </strong>}
|
||||
{data[v]}
|
||||
{i === a.length - 1 ? "" : ","}
|
||||
</p>
|
||||
)
|
||||
)}
|
||||
{Array.isArray(data) ? "]" : "}"}
|
||||
{!isLast ? "," : ""}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```jsx
|
||||
let data = {
|
||||
lorem: {
|
||||
ipsum: "dolor sit",
|
||||
amet: {
|
||||
consectetur: "adipiscing",
|
||||
elit: [
|
||||
"duis",
|
||||
"vitae",
|
||||
{
|
||||
semper: "orci"
|
||||
},
|
||||
{
|
||||
est: "sed ornare"
|
||||
},
|
||||
"etiam",
|
||||
["laoreet", "tincidunt"],
|
||||
["vestibulum", "ante"]
|
||||
]
|
||||
},
|
||||
ipsum: "primis"
|
||||
}
|
||||
};
|
||||
ReactDOM.render(<TreeView data={data} name='data'/>, document.getElementById("root"));
|
||||
```
|
||||
|
||||
<!-- tags: object,visual,state,recursion -->
|
||||
|
||||
<!-- expertise: 2 -->
|
||||
Reference in New Issue
Block a user