Skip to content

Instantly share code, notes, and snippets.

@StevenLangbroek
Created December 29, 2015 10:06
Show Gist options
  • Save StevenLangbroek/fc2a946c4c1c79db5e89 to your computer and use it in GitHub Desktop.
Save StevenLangbroek/fc2a946c4c1c79db5e89 to your computer and use it in GitHub Desktop.
Stupid simple higher-order function to help with pure components
/*
* 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>
)
@jdjuan
Copy link

jdjuan commented Jan 26, 2023

Thank you! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment