 # 30 seconds of React > Curated collection of useful React snippets that you can understand in 30 seconds or less. - Use Ctrl + F or command + F to search for a snippet. - Contributions welcome, please read the [contribution guide](CONTRIBUTING.md). - Snippets are written in React 16.8+, using hooks. ### Prerequisites To import a snippet into your project, you must import `React` and copy-paste the component's JavaScript code like this: ```js import React from 'react'; function MyComponent(props) { /* ... */ } ``` If there is any CSS related to your component, copy-paste it to a new file with the same name and the appropriate extension, then import it like this: ```js import './MyComponent.css'; ``` To render your component, make sure there is a node with and id of `"root"` present in your element (preferrably a `
| ID | Value |
|---|---|
| {i} | {val} |
| ` element. * Use `Array.prototype.map` to render each object in the `filteredData` array as a ` | ||
|---|---|---|
` for each key in the object.
```jsx
function MappedTable({ data, propertyNames }) {
let filteredData = data.map(v =>
Object.keys(v)
.filter(k => propertyNames.includes(k))
.reduce((acc, key) => ((acc[key] = v[key]), acc), {})
);
return (
Examples```jsx const people = [ { name: 'John', surname: 'Smith', age: 42 }, { name: 'Adam', surname: 'Smith', gender: 'male' } ]; const propertyNames = ['name', 'surname', 'age']; ReactDOM.render([⬆ Back to top](#table-of-contents) ## Input ### Input Renders an `` element that uses a callback function to pass its value to the parent component. * Use object destructuring to set defaults for certain attributes of the `` element. * Render an `` 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 function Input({ callback, type = 'text', disabled = false, readOnly = false, placeholder = '' }) { return ( callback(value)} /> ); } ``` Examples```jsx ReactDOM.render( console.log(val)} />, document.getElementById('root') ); ```[⬆ Back to top](#table-of-contents) ### LimitedTextarea 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` ` to wrap both the` |