Created
December 29, 2015 10:06
-
-
Save StevenLangbroek/fc2a946c4c1c79db5e89 to your computer and use it in GitHub Desktop.
Stupid simple higher-order function to help with pure components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * So, you're writing pure components now? Awesome right? RIGHT?!?! | |
| * Did you run into this yet? | |
| */ | |
| import React from 'react'; | |
| const Item = ({ | |
| item, | |
| openItem // a bound redux action creator | |
| }) => ( | |
| <div> | |
| <h1>{item.title</h1> | |
| <a | |
| href="#" | |
| onClick={() => openItem(item)} | |
| > | |
| Open Item | |
| </a> | |
| </div> | |
| ); | |
| /** | |
| * Now when you click on the link, it either screws up your nav, | |
| * or jumps the screen to the top if you're using HTML5 History. | |
| * Now, you probably thought of at least 2 approaches: | |
| * | |
| * - Turn your fancy pure component back into a normal component | |
| * - Add event.preventDefault() inline | |
| * | |
| * I don't lik either of these options, so I solved this with a | |
| * higher order function: | |
| */ | |
| const preventDefault = (fn, ...args) => (e) => { | |
| e.preventDefault(); | |
| fn(...args); | |
| }; | |
| const Item = ({ | |
| item, | |
| openItem | |
| }) => ( | |
| <div> | |
| <h1>{item.title</h1> | |
| <a href="#" onClick={preventDefault(openItem, item)}>Open Item</a> | |
| </div> | |
| ) | |
| // Or: | |
| const withEvent = (...methods) => (fn, ...args) => (e) => { | |
| methods.forEach(method => e[method]()); | |
| fn(...args); | |
| }; | |
| const Item = ({ | |
| item, | |
| openItem | |
| }) => ( | |
| <div> | |
| <h1>{item.title</h1> | |
| <a href="#" onClick={withEvent('preventDefault', 'stopPropagation')(openItem, item)}>Open Item</a> | |
| </div> | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! :)