Dataset in React

When life gives you lemons, you make lemonade. And when it doesn’t, hack your way around it. Such was the case with a piece of React code where the previous programmer passed some data-* attributes as props, then onto the JSX markup and later extract them from event.target in the event handlers (or also from the event.currentTarget or from native event). Now, React isn’t ready enough for this (as of January, 2017). The dataset property which are generally accessible via the HTMLElement.dataset property aren’t handled the DOM way.

While playing around wrappers, I had to find a workaround to pass the data-* props. I wrote a little hack to extract the data-* attributes using regex and some spread syntax to pass the dataset to both the outer wrapper, and the inner component.

Example:

render() {
  // Extract the keys present in the `props`
  // Filter the keys which have `data-` as prefix
  // and insert them into `dataset` object
  const dataset = {};
  const { state, props } = this;
  Object.keys(props).filter (value => {
    if (/data-\S+/gi.test(value)) {
       dataset[value] = props[value];
    }
  });
  return (
    <Wrapper {...dataset} onChange={this.handleChange} >
      <Component {...dataset} name="component-type-1">
      </Component>
    </Wrapper>
  )
}

The advantage – you can access the dataset in your handleChange method from the event.currentTarget and event.target. Visit this MDN link to know more about dataset.

Run a little gem: Faker

Faker @github is a ruby gem for generating fake data, albeit not guaranteed to be unique every time. It’s for general purposes of fake data generation.

# Instructions
# go to terminal
$ gem install faker

# start the interactive ruby shell
$ irb

# load the gem: Faker
irb(main):011:0> require 'Faker'
true
# returns 'true' if you're loading it for the first time.
irb(main):011:0> require 'Faker'
false
# false, because it's already loaded

# now, time to play around
irb(main):011:0> Faker::Name.name
=> "Brook Reichel"

irb(main):011:0> Faker::Address.city 
=> "West Brigitte"

# need a bitcoin wallet?
irb(main):014:0> Faker::Bitcoin.address
=> "1PfXhC3E64DYkdmYPKGwxziRh3ZzMKgzNn"


Update 1:

On the similar premises there are some other data generators you can have at your disposal