├── .gitattributes ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── languageFix.jsx ├── logo.png ├── snippet-template.md └── snippets ├── accordion.md ├── alert.md ├── auto-link.md ├── callto.md ├── carousel.md ├── collapse.md ├── controlled-input.md ├── count-down.md ├── data-list.md ├── data-table.md ├── file-drop.md ├── lazy-load-image.md ├── limited-textarea.md ├── limited-word-textarea.md ├── loader.md ├── mailto.md ├── mapped-table.md ├── modal.md ├── multiselect-checkbox.md ├── password-revealer.md ├── ripple-button.md ├── select.md ├── slider.md ├── star-rating.md ├── tabs.md ├── tag-input.md ├── text-area.md ├── toggle.md ├── tooltip.md ├── tree-view.md ├── uncontrolled-input.md ├── use-async.md ├── use-body-scroll-lock.md ├── use-click-inside.md ├── use-click-outside.md ├── use-component-did-mount.md ├── use-component-did-update.md ├── use-component-will-unmount.md ├── use-copy-to-clipboard.md ├── use-debounce.md ├── use-default.md ├── use-delayed-state.md ├── use-effect-once.md ├── use-error.md ├── use-event-listener.md ├── use-fetch.md ├── use-form.md ├── use-get-set.md ├── use-hash.md ├── use-hover.md ├── use-intersection-observer.md ├── use-interval.md ├── use-isomporphic-effect.md ├── use-key-press.md ├── use-local-storage.md ├── use-map.md ├── use-media-query.md ├── use-merge-state.md ├── use-mutation-observer.md ├── use-navigator-on-line.md ├── use-on-global-event.md ├── use-on-window-resize.md ├── use-on-window-scroll.md ├── use-persisted-state.md ├── use-portal.md ├── use-previous.md ├── use-request-animation-frame.md ├── use-script.md ├── use-search-param.md ├── use-session-storage.md ├── use-set.md ├── use-ssr.md ├── use-timeout.md ├── use-title.md ├── use-toggler.md ├── use-unload.md ├── use-update.md └── use-window-size.md /.gitattributes: -------------------------------------------------------------------------------- 1 | src/docs/* linguist-documentation 2 | scripts/* linguist-documentation 3 | gatsby-browser.js linguist-documentation 4 | gatsby-config.js linguist-documentation 5 | gatsby-node.js linguist-documentation 6 | gatsby-ssr.js linguist-documentation 7 | .travis/* linguist-documentation 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn 55 | yarn-error.log 56 | .pnp/ 57 | .pnp.js 58 | 59 | # Yarn Integrity file 60 | .yarn-integrity 61 | 62 | # dotenv environment variables file 63 | .env 64 | 65 | # next.js build output 66 | .next 67 | 68 | # gatsby files 69 | .cache/ 70 | public 71 | 72 | # Mac files 73 | .DS_Store -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at 30secondsofcode@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | **30 seconds of code** is powered by the community, so feel free to contribute in any way you can to help us! 4 | 5 | ## How you can help 6 | 7 | - Submit pull requests with new snippets (see guidelines below) or snippet updates (tags, descriptions, explanations, typos, examples, code improvements). 8 | - Open issues for things you want to see added, modified, discuss ideas or help out with existing issues. 9 | 10 | ## Ground rules 11 | 12 | Breaking any of these rules will result in your pull request being closed. Please follow these guidelines above all else: 13 | 14 | - **Always be polite and respectful to others** and try to follow the advice of the moderators/collaborators/owners. 15 | - **Only modify snippet files**, never modify the generated files in the `snippet_data` directory. 16 | - **Use the snippet template** to create new snippets, ensure they have the correct name and are in the correct location. 17 | - **Follow snippet format exactly**, otherwise your snippets will not be recognized correctly by the tools responsible for publishing them on the website. This includes such things as spacing and empty lines - if you accidentally make a mistake, consult the repository's [snippet template](snippet-template.md). 18 | - **Snippets should solve real-world problems**, no matter how simple and should be abstract enough to be applied to different scenarios. 19 | 20 | ## Snippet creation 21 | 22 | In order to create a new snippet, you should follow the steps below: 23 | 24 | - Create a copy of the [snippet template](snippet-template.md) in the `snippets` directory. 25 | - Change the name of the newly created file to the name of your snippet. 26 | - Edit the file, adding your snippet based on the guidelines. 27 | 28 | ## Snippet guidelines 29 | 30 | - Snippet must follow [these general writing guidelines](https://github.com/30-seconds/brand-and-design/blob/master/writing-guidelines.md). 31 | - Snippets must have all their frontmatter sections (title, tags etc.) filled. 32 | - Snippet titles must correspond to the filename and follow the language and repository's naming conventions. 33 | - Snippet tags must be comma-separated, contain a primary tag as seen on the website as their first tag. 34 | - Snippets must have their `firstSeen` dates formatted using [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). 35 | - Snippet descriptions must be short and to the point. Explain *what* the snippet does and detail *how* the snippet works and the language features used in it. 36 | - Snippet code and examples must be enclosed in appropriate, language-tagged blocks as shown in the snippet template, be short and use modern techniques and features. Also make sure to test your code before submitting. 37 | - If your snippet contains arguments with default parameters, explain what happens if they are omitted when calling the function and what the default case is. Specify default parameters for arguments only if necessary. 38 | - If your snippet uses recursion, use the `recursion` tag and explain the base cases. 39 | - Try to strike a balance between readability, brevity, and performance. 40 | - Always use soft tabs (2 spaces), never hard tabs. 41 | - Leave a single space after a comma (`,`) character (both in the description and code). 42 | - Define multiple variables on the same line, if possible. Use meaningful names (e.g. `letter` instead of `lt`) and follow existing conventions as seen in other snippets. Do not use trailing or leading underscores in variable names. 43 | - When describing snippets, refer to methods, using their full name. For example, use `Array.prototype.reduce()`, instead of `reduce()`. When using React Hooks, refer to the specific hooks with their full names, such as `useState()` and `useEffect()`. 44 | - When using `useState()`, try matching the name of the state variable to the function that sets it. For example, use `[isShown, setIsShown]` instead of `[isShown, setShown]`. When using `useEffect()`, only return a function if you have to clean up. In that case, name that function `cleanup()`. 45 | - Destructure your component's `props` whenever possible. If any of your props take default parameters, specify their default values in the destructured object. 46 | - Always use `const MyComponent = (props)` or `const MyComponent = ({ ... })` for function definitions. 47 | - Always use single quotes for string literals. Use template literals, instead, if necessary. 48 | - When rendering JSX, use double quotes, instead of single quotes. 49 | - Use strict equality checking (`===` and `!==` instead of `==` and `!=`). 50 | - Prefer using the ternary operator (`condition ? trueResult : falseResult`) instead of `if else` statements whenever possible. Avoid nesting ternary operators. 51 | - Never use `eval()`. Your snippet will be disqualified immediately. 52 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution 4.0 International Public License 58 | 59 | By exercising the Licensed Rights (defined below), You accept and agree 60 | to be bound by the terms and conditions of this Creative Commons 61 | Attribution 4.0 International Public License ("Public License"). To the 62 | extent this Public License may be interpreted as a contract, You are 63 | granted the Licensed Rights in consideration of Your acceptance of 64 | these terms and conditions, and the Licensor grants You such rights in 65 | consideration of benefits the Licensor receives from making the 66 | Licensed Material available under these terms and conditions. 67 | 68 | 69 | Section 1 -- Definitions. 70 | 71 | a. Adapted Material means material subject to Copyright and Similar 72 | Rights that is derived from or based upon the Licensed Material 73 | and in which the Licensed Material is translated, altered, 74 | arranged, transformed, or otherwise modified in a manner requiring 75 | permission under the Copyright and Similar Rights held by the 76 | Licensor. For purposes of this Public License, where the Licensed 77 | Material is a musical work, performance, or sound recording, 78 | Adapted Material is always produced where the Licensed Material is 79 | synched in timed relation with a moving image. 80 | 81 | b. Adapter's License means the license You apply to Your Copyright 82 | and Similar Rights in Your contributions to Adapted Material in 83 | accordance with the terms and conditions of this Public License. 84 | 85 | c. Copyright and Similar Rights means copyright and/or similar rights 86 | closely related to copyright including, without limitation, 87 | performance, broadcast, sound recording, and Sui Generis Database 88 | Rights, without regard to how the rights are labeled or 89 | categorized. For purposes of this Public License, the rights 90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 91 | Rights. 92 | 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. Share means to provide material to the public by any means or 116 | process that requires permission under the Licensed Rights, such 117 | as reproduction, public display, public performance, distribution, 118 | dissemination, communication, or importation, and to make material 119 | available to the public including in ways that members of the 120 | public may access the material from a place and at a time 121 | individually chosen by them. 122 | 123 | j. Sui Generis Database Rights means rights other than copyright 124 | resulting from Directive 96/9/EC of the European Parliament and of 125 | the Council of 11 March 1996 on the legal protection of databases, 126 | as amended and/or succeeded, as well as other essentially 127 | equivalent rights anywhere in the world. 128 | 129 | k. You means the individual or entity exercising the Licensed Rights 130 | under this Public License. Your has a corresponding meaning. 131 | 132 | 133 | Section 2 -- Scope. 134 | 135 | a. License grant. 136 | 137 | 1. Subject to the terms and conditions of this Public License, 138 | the Licensor hereby grants You a worldwide, royalty-free, 139 | non-sublicensable, non-exclusive, irrevocable license to 140 | exercise the Licensed Rights in the Licensed Material to: 141 | 142 | a. reproduce and Share the Licensed Material, in whole or 143 | in part; and 144 | 145 | b. produce, reproduce, and Share Adapted Material. 146 | 147 | 2. Exceptions and Limitations. For the avoidance of doubt, where 148 | Exceptions and Limitations apply to Your use, this Public 149 | License does not apply, and You do not need to comply with 150 | its terms and conditions. 151 | 152 | 3. Term. The term of this Public License is specified in Section 153 | 6(a). 154 | 155 | 4. Media and formats; technical modifications allowed. The 156 | Licensor authorizes You to exercise the Licensed Rights in 157 | all media and formats whether now known or hereafter created, 158 | and to make technical modifications necessary to do so. The 159 | Licensor waives and/or agrees not to assert any right or 160 | authority to forbid You from making technical modifications 161 | necessary to exercise the Licensed Rights, including 162 | technical modifications necessary to circumvent Effective 163 | Technological Measures. For purposes of this Public License, 164 | simply making modifications authorized by this Section 2(a) 165 | (4) never produces Adapted Material. 166 | 167 | 5. Downstream recipients. 168 | 169 | a. Offer from the Licensor -- Licensed Material. Every 170 | recipient of the Licensed Material automatically 171 | receives an offer from the Licensor to exercise the 172 | Licensed Rights under the terms and conditions of this 173 | Public License. 174 | 175 | b. No downstream restrictions. You may not offer or impose 176 | any additional or different terms or conditions on, or 177 | apply any Effective Technological Measures to, the 178 | Licensed Material if doing so restricts exercise of the 179 | Licensed Rights by any recipient of the Licensed 180 | Material. 181 | 182 | 6. No endorsement. Nothing in this Public License constitutes or 183 | may be construed as permission to assert or imply that You 184 | are, or that Your use of the Licensed Material is, connected 185 | with, or sponsored, endorsed, or granted official status by, 186 | the Licensor or others designated to receive attribution as 187 | provided in Section 3(a)(1)(A)(i). 188 | 189 | b. Other rights. 190 | 191 | 1. Moral rights, such as the right of integrity, are not 192 | licensed under this Public License, nor are publicity, 193 | privacy, and/or other similar personality rights; however, to 194 | the extent possible, the Licensor waives and/or agrees not to 195 | assert any such rights held by the Licensor to the limited 196 | extent necessary to allow You to exercise the Licensed 197 | Rights, but not otherwise. 198 | 199 | 2. Patent and trademark rights are not licensed under this 200 | Public License. 201 | 202 | 3. To the extent possible, the Licensor waives any right to 203 | collect royalties from You for the exercise of the Licensed 204 | Rights, whether directly or through a collecting society 205 | under any voluntary or waivable statutory or compulsory 206 | licensing scheme. In all other cases the Licensor expressly 207 | reserves any right to collect such royalties. 208 | 209 | 210 | Section 3 -- License Conditions. 211 | 212 | Your exercise of the Licensed Rights is expressly made subject to the 213 | following conditions. 214 | 215 | a. Attribution. 216 | 217 | 1. If You Share the Licensed Material (including in modified 218 | form), You must: 219 | 220 | a. retain the following if it is supplied by the Licensor 221 | with the Licensed Material: 222 | 223 | i. identification of the creator(s) of the Licensed 224 | Material and any others designated to receive 225 | attribution, in any reasonable manner requested by 226 | the Licensor (including by pseudonym if 227 | designated); 228 | 229 | ii. a copyright notice; 230 | 231 | iii. a notice that refers to this Public License; 232 | 233 | iv. a notice that refers to the disclaimer of 234 | warranties; 235 | 236 | v. a URI or hyperlink to the Licensed Material to the 237 | extent reasonably practicable; 238 | 239 | b. indicate if You modified the Licensed Material and 240 | retain an indication of any previous modifications; and 241 | 242 | c. indicate the Licensed Material is licensed under this 243 | Public License, and include the text of, or the URI or 244 | hyperlink to, this Public License. 245 | 246 | 2. You may satisfy the conditions in Section 3(a)(1) in any 247 | reasonable manner based on the medium, means, and context in 248 | which You Share the Licensed Material. For example, it may be 249 | reasonable to satisfy the conditions by providing a URI or 250 | hyperlink to a resource that includes the required 251 | information. 252 | 253 | 3. If requested by the Licensor, You must remove any of the 254 | information required by Section 3(a)(1)(A) to the extent 255 | reasonably practicable. 256 | 257 | 4. If You Share Adapted Material You produce, the Adapter's 258 | License You apply must not prevent recipients of the Adapted 259 | Material from complying with this Public License. 260 | 261 | 262 | Section 4 -- Sui Generis Database Rights. 263 | 264 | Where the Licensed Rights include Sui Generis Database Rights that 265 | apply to Your use of the Licensed Material: 266 | 267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 268 | to extract, reuse, reproduce, and Share all or a substantial 269 | portion of the contents of the database; 270 | 271 | b. if You include all or a substantial portion of the database 272 | contents in a database in which You have Sui Generis Database 273 | Rights, then the database in which You have Sui Generis Database 274 | Rights (but not its individual contents) is Adapted Material; and 275 | 276 | c. You must comply with the conditions in Section 3(a) if You Share 277 | all or a substantial portion of the contents of the database. 278 | 279 | For the avoidance of doubt, this Section 4 supplements and does not 280 | replace Your obligations under this Public License where the Licensed 281 | Rights include other Copyright and Similar Rights. 282 | 283 | 284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 285 | 286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 296 | 297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 306 | 307 | c. The disclaimer of warranties and limitation of liability provided 308 | above shall be interpreted in a manner that, to the extent 309 | possible, most closely approximates an absolute disclaimer and 310 | waiver of all liability. 311 | 312 | 313 | Section 6 -- Term and Termination. 314 | 315 | a. This Public License applies for the term of the Copyright and 316 | Similar Rights licensed here. However, if You fail to comply with 317 | this Public License, then Your rights under this Public License 318 | terminate automatically. 319 | 320 | b. Where Your right to use the Licensed Material has terminated under 321 | Section 6(a), it reinstates: 322 | 323 | 1. automatically as of the date the violation is cured, provided 324 | it is cured within 30 days of Your discovery of the 325 | violation; or 326 | 327 | 2. upon express reinstatement by the Licensor. 328 | 329 | For the avoidance of doubt, this Section 6(b) does not affect any 330 | right the Licensor may have to seek remedies for Your violations 331 | of this Public License. 332 | 333 | c. For the avoidance of doubt, the Licensor may also offer the 334 | Licensed Material under separate terms or conditions or stop 335 | distributing the Licensed Material at any time; however, doing so 336 | will not terminate this Public License. 337 | 338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 339 | License. 340 | 341 | 342 | Section 7 -- Other Terms and Conditions. 343 | 344 | a. The Licensor shall not be bound by any additional or different 345 | terms or conditions communicated by You unless expressly agreed. 346 | 347 | b. Any arrangements, understandings, or agreements regarding the 348 | Licensed Material not stated herein are separate from and 349 | independent of the terms and conditions of this Public License. 350 | 351 | 352 | Section 8 -- Interpretation. 353 | 354 | a. For the avoidance of doubt, this Public License does not, and 355 | shall not be interpreted to, reduce, limit, restrict, or impose 356 | conditions on any use of the Licensed Material that could lawfully 357 | be made without permission under this Public License. 358 | 359 | b. To the extent possible, if any provision of this Public License is 360 | deemed unenforceable, it shall be automatically reformed to the 361 | minimum extent necessary to make it enforceable. If the provision 362 | cannot be reformed, it shall be severed from this Public License 363 | without affecting the enforceability of the remaining terms and 364 | conditions. 365 | 366 | c. No term or condition of this Public License will be waived and no 367 | failure to comply consented to unless expressly agreed to by the 368 | Licensor. 369 | 370 | d. Nothing in this Public License constitutes or may be interpreted 371 | as a limitation upon, or waiver of, any privileges and immunities 372 | that apply to the Licensor or You, including from the legal 373 | processes of any jurisdiction or authority. 374 | 375 | 376 | ======================================================================= 377 | 378 | Creative Commons is not a party to its public 379 | licenses. Notwithstanding, Creative Commons may elect to apply one of 380 | its public licenses to material it publishes and in those instances 381 | will be considered the “Licensor.” The text of the Creative Commons 382 | public licenses is dedicated to the public domain under the CC0 Public 383 | Domain Dedication. Except for the limited purpose of indicating that 384 | material is shared under a Creative Commons public license or as 385 | otherwise permitted by the Creative Commons policies published at 386 | creativecommons.org/policies, Creative Commons does not authorize the 387 | use of the trademark "Creative Commons" or any other trademark or logo 388 | of Creative Commons without its prior written consent including, 389 | without limitation, in connection with any unauthorized modifications 390 | to any of its public licenses or any other arrangements, 391 | understandings, or agreements concerning use of licensed material. For 392 | the avoidance of doubt, this paragraph does not form part of the 393 | public licenses. 394 | 395 | Creative Commons may be contacted at creativecommons.org. 396 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | > **IMPORTANT NOTICE:** 2 | > 3 | > As of May, 2023, all 30-seconds content repositories have been merged into [30-seconds-of-code](https://github.com/30-seconds/30-seconds-of-code). 4 | > 5 | > Please watch, star and follow relevant activity there. 6 | 7 | [![Logo](/logo.png)](https://30secondsofcode.org/react/p/1) 8 | 9 | # 30 seconds of code 10 | 11 | > Short React code snippets for all your development needs 12 | 13 | * Visit [our website](https://30secondsofcode.org) to view our snippet collection. 14 | * Use the [Search page](https://30secondsofcode.org/search) to find snippets that suit your needs. You can search by name, tag, language or using a snippet's description. Just start typing a term and see what comes up. 15 | * Browse the [React Snippet collection](https://30secondsofcode.org/react/p/1) to see all the snippets in this project or click individual tags at the top of the same page to narrow down your search to a specific tag. 16 | * Click on each snippet card to view the whole snippet, including code, explanation and examples. 17 | * You can use the button at the bottom of a snippet card to view the snippet in Codepen. 18 | * If you like the project, give it a star. It means a lot to the people maintaining it. 19 | 20 | ## Want to contribute? 21 | 22 | * If you want to help us improve, take a minute to read the [Contribution Guidelines](/CONTRIBUTING.md) first. 23 | * Use the [Snippet Template](/snippet-template.md) to add new snippets to the collection. 24 | * If you find a problem with a specific snippet, please [open an issue](https://github.com/30-seconds/30-seconds-of-react/issues/new). 25 | * If you find a problem with the website, please [report it in the web repository](https://github.com/30-seconds/30-seconds-web/issues/new). 26 | 27 | ## Credits 28 | 29 | * This repository is maintained by the [30 seconds of code organization on GitHub](https://github.com/30-seconds). 30 | * All snippets are licensed under the CC-BY-4.0 License, unless explicitly stated otherwise. 31 | * Logos, names and trademarks are not to be used without the explicit consent of the owners of the 30 seconds of code GitHub organization. 32 | * Our website is powered by [Netlify](https://www.netlify.com/), [Next.js](https://nextjs.org/) & [GitHub](https://github.com/). 33 | -------------------------------------------------------------------------------- /languageFix.jsx: -------------------------------------------------------------------------------- 1 | console.log('This file is here only to tag the repository language. Do not delete, please!'); 2 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Chalarangelo/30-seconds-of-react/a5e673afbaddd31d6f80b2218ab16d0a82514cf5/logo.png -------------------------------------------------------------------------------- /snippet-template.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Component Name 3 | type: snippet 4 | tags: [components,state,effect] 5 | cover: image 6 | dateModified: 2021-06-13T05:00:00-04:00 7 | --- 8 | 9 | Explain briefly what the snippet does. 10 | 11 | - Explain briefly how the snippet works. 12 | - Use bullet points for your snippet's explanation. 13 | - Try to explain everything briefly but clearly. 14 | 15 | ```jsx 16 | const ComponentName = props => { 17 | const [state, setState] = React.useState(null); 18 | React.useEffect(() => { 19 | setState(0); 20 | }); 21 | return
{props}
; 22 | } 23 | ``` 24 | 25 | ```jsx 26 | ReactDOM.createRoot(document.getElementById('root')).render( 27 | 28 | ); 29 | ``` 30 | -------------------------------------------------------------------------------- /snippets/accordion.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Collapsible accordion 3 | type: snippet 4 | tags: [components,children,state] 5 | cover: beach-pineapple 6 | dateModified: 2021-10-13T19:29:39+02:00 7 | --- 8 | 9 | Renders an accordion menu with multiple collapsible content elements. 10 | 11 | - Define an `AccordionItem` component, that renders a ` 41 |
45 | {children} 46 |
47 | 48 | ); 49 | }; 50 | 51 | const Accordion = ({ defaultIndex, onItemClick, children }) => { 52 | const [bindIndex, setBindIndex] = React.useState(defaultIndex); 53 | 54 | const changeItem = itemIndex => { 55 | if (typeof onItemClick === 'function') onItemClick(itemIndex); 56 | if (itemIndex !== bindIndex) setBindIndex(itemIndex); 57 | }; 58 | const items = children.filter(item => item.type.name === 'AccordionItem'); 59 | 60 | return ( 61 | <> 62 | {items.map(({ props }) => ( 63 | changeItem(props.index)} 67 | children={props.children} 68 | /> 69 | ))} 70 | 71 | ); 72 | }; 73 | ``` 74 | 75 | ```jsx 76 | ReactDOM.createRoot(document.getElementById('root')).render( 77 | 78 | 79 | Lorem ipsum 80 | 81 | 82 | Dolor sit amet 83 | 84 | 85 | ); 86 | ``` 87 | -------------------------------------------------------------------------------- /snippets/alert.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Closable alert 3 | type: snippet 4 | tags: [components,state,effect] 5 | cover: flower-portrait-1 6 | dateModified: 2021-01-07T23:57:13+02:00 7 | --- 8 | 9 | Renders an alert component with `type` prop. 10 | 11 | - Use the `useState()` hook to create the `isShown` and `isLeaving` state variables and set both to `false` initially. 12 | - Define `timeoutId` to keep the timer instance for clearing on component unmount. 13 | - Use the `useEffect()` hook to update the value of `isShown` to `true` and clear the interval by using `timeoutId` when the component is unmounted. 14 | - Define a `closeAlert` function to set the component as removed from the DOM by displaying a fading out animation and set `isShown` to `false` via `setTimeout()`. 15 | 16 | ```css 17 | @keyframes leave { 18 | 0% { opacity: 1 } 19 | 100% { opacity: 0 } 20 | } 21 | 22 | .alert { 23 | padding: 0.75rem 0.5rem; 24 | margin-bottom: 0.5rem; 25 | text-align: left; 26 | padding-right: 40px; 27 | border-radius: 4px; 28 | font-size: 16px; 29 | position: relative; 30 | } 31 | 32 | .alert.warning { 33 | color: #856404; 34 | background-color: #fff3cd; 35 | border-color: #ffeeba; 36 | } 37 | 38 | .alert.error { 39 | color: #721c24; 40 | background-color: #f8d7da; 41 | border-color: #f5c6cb; 42 | } 43 | 44 | .alert.leaving { 45 | animation: leave 0.5s forwards; 46 | } 47 | 48 | .alert .close { 49 | position: absolute; 50 | top: 0; 51 | right: 0; 52 | padding: 0 0.75rem; 53 | color: #333; 54 | border: 0; 55 | height: 100%; 56 | cursor: pointer; 57 | background: none; 58 | font-weight: 600; 59 | font-size: 16px; 60 | } 61 | 62 | .alert .close::after { 63 | content: 'x'; 64 | } 65 | ``` 66 | 67 | ```jsx 68 | const Alert = ({ isDefaultShown = false, timeout = 250, type, message }) => { 69 | const [isShown, setIsShown] = React.useState(isDefaultShown); 70 | const [isLeaving, setIsLeaving] = React.useState(false); 71 | 72 | let timeoutId = null; 73 | 74 | React.useEffect(() => { 75 | setIsShown(true); 76 | return () => { 77 | clearTimeout(timeoutId); 78 | }; 79 | }, [isDefaultShown, timeout, timeoutId]); 80 | 81 | const closeAlert = () => { 82 | setIsLeaving(true); 83 | timeoutId = setTimeout(() => { 84 | setIsLeaving(false); 85 | setIsShown(false); 86 | }, timeout); 87 | }; 88 | 89 | return ( 90 | isShown && ( 91 |
95 |
98 | ) 99 | ); 100 | }; 101 | ``` 102 | 103 | ```jsx 104 | ReactDOM.createRoot(document.getElementById('root')).render( 105 | 106 | ); 107 | ``` 108 | -------------------------------------------------------------------------------- /snippets/auto-link.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Automatic text linking 3 | type: snippet 4 | tags: [components,fragment,regexp] 5 | author: chalarangelo 6 | cover: red-petals 7 | dateModified: 2020-11-03T20:42:15+02:00 8 | --- 9 | 10 | Renders a string as plaintext, with URLs converted to appropriate link elements. 11 | 12 | - Use `String.prototype.split()` and `String.prototype.match()` with a regular expression to find URLs in a string. 13 | - Return matched URLs rendered as `` elements, dealing with missing protocol prefixes if necessary. 14 | - Render the rest of the string as plaintext. 15 | 16 | ```jsx 17 | const AutoLink = ({ text }) => { 18 | 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; 19 | 20 | return ( 21 | <> 22 | {text.split(delimiter).map(word => { 23 | const match = word.match(delimiter); 24 | if (match) { 25 | const url = match[0]; 26 | return ( 27 | {url} 28 | ); 29 | } 30 | return word; 31 | })} 32 | 33 | ); 34 | }; 35 | ``` 36 | 37 | ```jsx 38 | ReactDOM.createRoot(document.getElementById('root')).render( 39 | 40 | ); 41 | ``` 42 | -------------------------------------------------------------------------------- /snippets/callto.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Callable telephone link 3 | type: snippet 4 | tags: [components] 5 | author: chalarangelo 6 | unlisted: true 7 | cover: rabbit-call 8 | dateModified: 2021-01-04T12:32:47+02:00 9 | --- 10 | 11 | Renders a link formatted to call a phone number (`tel:` link). 12 | 13 | - Use `phone` to create a `` element with an appropriate `href` attribute. 14 | - Render the link with `children` as its content. 15 | 16 | ```jsx 17 | const Callto = ({ phone, children }) => { 18 | return {children}; 19 | }; 20 | ``` 21 | 22 | ```jsx 23 | ReactDOM.createRoot(document.getElementById('root')).render( 24 | Call me! 25 | ); 26 | ``` 27 | -------------------------------------------------------------------------------- /snippets/carousel.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Carousel 3 | type: snippet 4 | tags: [components,children,state,effect] 5 | cover: shell-focus 6 | dateModified: 2020-11-03T20:42:15+02:00 7 | --- 8 | 9 | Renders a carousel component. 10 | 11 | - Use the `useState()` hook to create the `active` state variable and give it a value of `0` (index of the first item). 12 | - Use the `useEffect()` hook to update the value of `active` to the index of the next item, using `setTimeout()`. 13 | - Compute the `className` for each carousel item while mapping over them and applying it accordingly. 14 | - Render the carousel items using `React.cloneElement()` and pass down `...rest` along with the computed `className`. 15 | 16 | ```css 17 | .carousel { 18 | position: relative; 19 | } 20 | 21 | .carousel-item { 22 | position: absolute; 23 | visibility: hidden; 24 | } 25 | 26 | .carousel-item.visible { 27 | visibility: visible; 28 | } 29 | ``` 30 | 31 | ```jsx 32 | const Carousel = ({ carouselItems, ...rest }) => { 33 | const [active, setActive] = React.useState(0); 34 | let scrollInterval = null; 35 | 36 | React.useEffect(() => { 37 | scrollInterval = setTimeout(() => { 38 | setActive((active + 1) % carouselItems.length); 39 | }, 2000); 40 | return () => clearTimeout(scrollInterval); 41 | }); 42 | 43 | return ( 44 |
45 | {carouselItems.map((item, index) => { 46 | const activeClass = active === index ? ' visible' : ''; 47 | return React.cloneElement(item, { 48 | ...rest, 49 | className: `carousel-item${activeClass}` 50 | }); 51 | })} 52 |
53 | ); 54 | }; 55 | ``` 56 | 57 | ```jsx 58 | ReactDOM.createRoot(document.getElementById('root')).render( 59 | carousel item 1, 62 |
carousel item 2
, 63 |
carousel item 3
64 | ]} 65 | /> 66 | ); 67 | ``` 68 | -------------------------------------------------------------------------------- /snippets/collapse.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Collapsible content 3 | type: snippet 4 | tags: [components,children,state] 5 | cover: washed-ashore 6 | dateModified: 2021-10-13T19:29:39+02:00 7 | --- 8 | 9 | Renders a component with collapsible content. 10 | 11 | - Use the `useState()` hook to create the `isCollapsed` state variable. Give it an initial value of `collapsed`. 12 | - Use the ` 43 |
47 | {children} 48 |
49 | 50 | ); 51 | }; 52 | ``` 53 | 54 | ```jsx 55 | ReactDOM.createRoot(document.getElementById('root')).render( 56 | 57 |

This is a collapse

58 |

Hello world!

59 |
60 | ); 61 | ``` 62 | -------------------------------------------------------------------------------- /snippets/controlled-input.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Controlled input field 3 | type: snippet 4 | tags: [components,input] 5 | cover: digital-nomad-5 6 | dateModified: 2020-11-03T21:08:39+02:00 7 | --- 8 | 9 | Renders a controlled `` element that uses a callback function to inform its parent about value updates. 10 | 11 | - Use the `value` passed down from the parent as the controlled input field's value. 12 | - Use the `onChange` event to fire the `onValueChange` callback and send the new value to the parent. 13 | - The parent must update the input field's `value` prop in order for its value to change on user input. 14 | 15 | ```jsx 16 | const ControlledInput = ({ value, onValueChange, ...rest }) => { 17 | return ( 18 | onValueChange(value)} 21 | {...rest} 22 | /> 23 | ); 24 | }; 25 | ``` 26 | 27 | ```jsx 28 | const Form = () => { 29 | const [value, setValue] = React.useState(''); 30 | 31 | return ( 32 | 38 | ); 39 | }; 40 | 41 | ReactDOM.createRoot(document.getElementById('root')).render( 42 |
43 | ); 44 | ``` 45 | -------------------------------------------------------------------------------- /snippets/count-down.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Countdown timer 3 | type: snippet 4 | tags: [components,state] 5 | cover: sea-view-2 6 | dateModified: 2021-10-13T19:29:39+02:00 7 | --- 8 | 9 | Renders a countdown timer that prints a message when it reaches zero. 10 | 11 | - Use the `useState()` hook to create a state variable to hold the time value. Initialize it from the props and destructure it into its components. 12 | - Use the `useState()` hook to create the `paused` and `over` state variables, used to prevent the timer from ticking if it's paused or the time has run out. 13 | - Create a method `tick`, that updates the time values based on the current value (i.e. decreasing the time by one second). 14 | - Create a method `reset`, that resets all state variables to their initial states. 15 | - Use the the `useEffect()` hook to call the `tick` method every second via the use of `setInterval()` and use `clearInterval()` to clean up when the component is unmounted. 16 | - Use `String.prototype.padStart()` to pad each part of the time array to two characters to create the visual representation of the timer. 17 | 18 | ```jsx 19 | const CountDown = ({ hours = 0, minutes = 0, seconds = 0 }) => { 20 | const [paused, setPaused] = React.useState(false); 21 | const [over, setOver] = React.useState(false); 22 | const [[h, m, s], setTime] = React.useState([hours, minutes, seconds]); 23 | 24 | const tick = () => { 25 | if (paused || over) return; 26 | if (h === 0 && m === 0 && s === 0) setOver(true); 27 | else if (m === 0 && s === 0) { 28 | setTime([h - 1, 59, 59]); 29 | } else if (s == 0) { 30 | setTime([h, m - 1, 59]); 31 | } else { 32 | setTime([h, m, s - 1]); 33 | } 34 | }; 35 | 36 | const reset = () => { 37 | setTime([parseInt(hours), parseInt(minutes), parseInt(seconds)]); 38 | setPaused(false); 39 | setOver(false); 40 | }; 41 | 42 | React.useEffect(() => { 43 | const timerID = setInterval(() => tick(), 1000); 44 | return () => clearInterval(timerID); 45 | }); 46 | 47 | return ( 48 |
49 |

{`${h.toString().padStart(2, '0')}:${m 50 | .toString() 51 | .padStart(2, '0')}:${s.toString().padStart(2, '0')}`}

52 |
{over ? "Time's up!" : ''}
53 | 56 | 57 |
58 | ); 59 | }; 60 | ``` 61 | 62 | ```jsx 63 | ReactDOM.createRoot(document.getElementById('root')).render( 64 | 65 | ); 66 | ``` 67 | -------------------------------------------------------------------------------- /snippets/data-list.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Data list 3 | type: snippet 4 | tags: [components] 5 | cover: interior-14 6 | dateModified: 2020-11-03T21:26:34+02:00 7 | --- 8 | 9 | Renders a list of elements from an array of primitives. 10 | 11 | - Use the value of the `isOrdered` prop to conditionally render an `
    ` or a `
      ` list. 12 | - Use `Array.prototype.map()` to render every item in `data` as a `
    • ` element with an appropriate `key`. 13 | 14 | ```jsx 15 | const DataList = ({ isOrdered = false, data }) => { 16 | const list = data.map((val, i) =>
    • {val}
    • ); 17 | return isOrdered ?
        {list}
      :
        {list}
      ; 18 | }; 19 | ``` 20 | 21 | ```jsx 22 | const names = ['John', 'Paul', 'Mary']; 23 | ReactDOM.createRoot(document.getElementById('root')).render( 24 | <> 25 | 26 | 27 | 28 | ); 29 | ``` 30 | -------------------------------------------------------------------------------- /snippets/data-table.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Data table 3 | type: snippet 4 | tags: [components] 5 | cover: armchair 6 | dateModified: 2020-11-03T21:26:34+02:00 7 | --- 8 | 9 | Renders a table with rows dynamically created from an array of primitives. 10 | 11 | - Render a `` element with two columns (`ID` and `Value`). 12 | - Use `Array.prototype.map()` to render every item in `data` as a `` element with an appropriate `key`. 13 | 14 | ```jsx 15 | const DataTable = ({ data }) => { 16 | return ( 17 |
      18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | {data.map((val, i) => ( 26 | 27 | 28 | 29 | 30 | ))} 31 | 32 |
      IDValue
      {i}{val}
      33 | ); 34 | }; 35 | ``` 36 | 37 | ```jsx 38 | const people = ['John', 'Jesse']; 39 | ReactDOM.createRoot(document.getElementById('root')).render( 40 | 41 | ); 42 | ``` 43 | -------------------------------------------------------------------------------- /snippets/file-drop.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: File drag and drop area 3 | type: snippet 4 | tags: [components,input,state,effect,event] 5 | author: chalarangelo 6 | cover: man-red-sunset 7 | dateModified: 2021-10-13T19:29:39+02:00 8 | --- 9 | 10 | Renders a file drag and drop component for a single file. 11 | 12 | - Create a ref, called `dropRef` and bind it to the component's wrapper. 13 | - Use the `useState()` hook to create the `drag` and `filename` variables. Initialize them to `false` and `''` respectively. 14 | - 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. 15 | - Create the `handleDrag`, `handleDragIn`, `handleDragOut` and `handleDrop` methods to handle drag and drop functionality. 16 | - `handleDrag` prevents the browser from opening the dragged file. `handleDragIn` and `handleDragOut` handle the dragged file entering and exiting the component. `handleDrop` handles the file being dropped and passes it to `onDrop`. 17 | - Use the `useEffect()` hook to handle each of the drag and drop events using the previously created methods. 18 | 19 | ```css 20 | .filedrop { 21 | min-height: 120px; 22 | border: 3px solid #d3d3d3; 23 | text-align: center; 24 | font-size: 24px; 25 | padding: 32px; 26 | border-radius: 4px; 27 | } 28 | 29 | .filedrop.drag { 30 | border: 3px dashed #1e90ff; 31 | } 32 | 33 | .filedrop.ready { 34 | border: 3px solid #32cd32; 35 | } 36 | ``` 37 | 38 | ```jsx 39 | const FileDrop = ({ onDrop }) => { 40 | const [drag, setDrag] = React.useState(false); 41 | const [filename, setFilename] = React.useState(''); 42 | let dropRef = React.createRef(); 43 | let dragCounter = 0; 44 | 45 | const handleDrag = e => { 46 | e.preventDefault(); 47 | e.stopPropagation(); 48 | }; 49 | 50 | const handleDragIn = e => { 51 | e.preventDefault(); 52 | e.stopPropagation(); 53 | dragCounter++; 54 | if (e.dataTransfer.items && e.dataTransfer.items.length > 0) setDrag(true); 55 | }; 56 | 57 | const handleDragOut = e => { 58 | e.preventDefault(); 59 | e.stopPropagation(); 60 | dragCounter--; 61 | if (dragCounter === 0) setDrag(false); 62 | }; 63 | 64 | const handleDrop = e => { 65 | e.preventDefault(); 66 | e.stopPropagation(); 67 | setDrag(false); 68 | if (e.dataTransfer.files && e.dataTransfer.files.length > 0) { 69 | onDrop(e.dataTransfer.files[0]); 70 | setFilename(e.dataTransfer.files[0].name); 71 | e.dataTransfer.clearData(); 72 | dragCounter = 0; 73 | } 74 | }; 75 | 76 | React.useEffect(() => { 77 | let div = dropRef.current; 78 | div.addEventListener('dragenter', handleDragIn); 79 | div.addEventListener('dragleave', handleDragOut); 80 | div.addEventListener('dragover', handleDrag); 81 | div.addEventListener('drop', handleDrop); 82 | return () => { 83 | div.removeEventListener('dragenter', handleDragIn); 84 | div.removeEventListener('dragleave', handleDragOut); 85 | div.removeEventListener('dragover', handleDrag); 86 | div.removeEventListener('drop', handleDrop); 87 | }; 88 | }); 89 | 90 | return ( 91 |
      97 | {filename && !drag ?
      {filename}
      :
      Drop a file here!
      } 98 |
      99 | ); 100 | }; 101 | ``` 102 | 103 | ```jsx 104 | ReactDOM.createRoot(document.getElementById('root')).render( 105 | 106 | ); 107 | ``` 108 | -------------------------------------------------------------------------------- /snippets/lazy-load-image.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Lazy-loading image 3 | type: snippet 4 | tags: [components,effect,state] 5 | cover: strawberries 6 | author: chalarangelo 7 | dateModified: 2022-07-29T05:00:00-04:00 8 | --- 9 | 10 | Renders an image that supports lazy loading. 11 | 12 | - Use the `useState()` hook to create a stateful value that indicates if the image has been loaded. 13 | - Use the `useEffect()` hook to check if the `HTMLImageElement.prototype` contains `'loading'`, effectively checking if lazy loading is supported natively. If not, create a new `IntersectionObserver` and use `IntersectionObserver.observer()` to observer the `` element. Use the `return` value of the hook to clean up when the component unmounts. 14 | - Use the `useCallback()` hook to memoize a callback function for the `IntersectionObserver`. This callback will update the `isLoaded` state variable and use `IntersectionObserver.disconnect()` to disconnect the `IntersectionObserver` instance. 15 | - Use the `useRef()` hook to create two refs. One will hold the `` element and the other the `IntersectionObserver` instance, if necessary. 16 | - Finally, render the `` element with the given attributes. Apply `loading='lazy'` to make it load lazily, if necessary. Use `isLoaded` to determine the value of the `src` attribute. 17 | 18 | ```jsx 19 | const LazyLoadImage = ({ 20 | alt, 21 | src, 22 | className, 23 | loadInitially = false, 24 | observerOptions = { root: null, rootMargin: '200px 0px' }, 25 | ...props 26 | }) => { 27 | const observerRef = React.useRef(null); 28 | const imgRef = React.useRef(null); 29 | const [isLoaded, setIsLoaded] = React.useState(loadInitially); 30 | 31 | const observerCallback = React.useCallback( 32 | entries => { 33 | if (entries[0].isIntersecting) { 34 | observerRef.current.disconnect(); 35 | setIsLoaded(true); 36 | } 37 | }, 38 | [observerRef] 39 | ); 40 | 41 | React.useEffect(() => { 42 | if (loadInitially) return; 43 | 44 | if ('loading' in HTMLImageElement.prototype) { 45 | setIsLoaded(true); 46 | return; 47 | } 48 | 49 | observerRef.current = new IntersectionObserver( 50 | observerCallback, 51 | observerOptions 52 | ); 53 | observerRef.current.observe(imgRef.current); 54 | return () => { 55 | observerRef.current.disconnect(); 56 | }; 57 | }, []); 58 | 59 | return ( 60 | {alt} 68 | ); 69 | }; 70 | ``` 71 | 72 | ```jsx 73 | ReactDOM.createRoot(document.getElementById('root')).render( 74 | 78 | ); 79 | ``` 80 | -------------------------------------------------------------------------------- /snippets/limited-textarea.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Textarea with character limit 3 | type: snippet 4 | tags: [components,state,callback,event] 5 | cover: flower-portrait-2 6 | dateModified: 2021-10-13T19:29:39+02:00 7 | --- 8 | 9 | Renders a textarea component with a character limit. 10 | 11 | - Use the `useState()` hook to create the `content` state variable. Set its value to that of `value` prop, trimmed down to `limit` characters. 12 | - Create a method `setFormattedContent`, which trims the content down to `limit` characters and memoize it, using the `useCallback()` hook. 13 | - Bind the `onChange` event of the `