picture of Josh Dzielak in 2016

Hi! I'm Josh Dzielak, writing here about technology and culture. Find me also on Twitter, Medium, Speakerdeck and Github.

Demystifying enter key submission for React forms with multiple buttons

There are some common problems that developers run into when trying to get enter key submission to work for forms with multiple buttons. This is true for both React and plain HTML.

Take a form with "Cancel" and "Save" buttons as an example. There are at least three things that can go wrong:

  • The enter key does nothing
  • The enter key causes a cancel instead of a save
  • The enter key causes both a cancel and a save

This is with just two buttons. If the form has more than two buttons the situation can get uglier. Thankfully, there are just a few things to know to get the right behavior every time. Keep reading to learn what they are.

Fact 1: <button> is type="submit" by default

HTML button tags are not type="button" by default. They're type="submit". (See <button> on MDN.) It's easy to forget to add a type attribute to your buttons, and if you don't then they'll all be submit buttons. This little-known fact is where the problems start, which are then compounded by this next fact.

Fact 2: Pressing the enter key triggers the click handler of the first type="submit" button

Yep, a keypress causes a click event to fire. It's not intuitive, it's just HTML.

Furthermore, it's the DOM order that determines which button's onClick event is called. If the Save button comes before the Cancel button, the Save button's onClick will be called. If the Cancel button comes first, the Cancel button's onClick will be called. This makes it very easy to introduce bugs just by switching the order of elements.

Broken Example

Let's look at an example React component that renders a form. FormOne looks innocent enough, but it has a serious problem. The enter key will cause the form submission to be cancelled, not saved.

var FormOne = React.createClass({
  onSave: function(event) {
    event.preventDefault();
    console.log("onSave handler called");
  },
  onCancel: function(event) {
   event.preventDefault();
   console.log("onCancel handler called");
  },
  render: function() {
    return (
      <form onSubmit={this.onSave}>
        <input type="text" />
        <button onClick={this.onCancel}>Cancel</button>
        <button type="submit">Save</button>
      </form>
    );
  }
});

Try it on Codepen.

Because the Cancel button is before the Save button and both are type="submit" (remember Fact 1), the enter key will trigger the onClick event of the Cancel button.

The onCancel event handler prevents the default event, so the form's onSubmit will never be called. If the onCancel did not prevent the default event, both the onCancel and the onSave handlers would be called.

Fixed Example

Let's look at another form, FormTwo. There is only one change—the type of the Cancel button is now type="button". This small difference makes all the difference. The first type="submit" button is now the Save button, which does not have an onClick handler. It doesn't need one because the form's onSubmit handler will be called, which has been bound to the onSave method for saving the form.

var FormTwo = React.createClass({
  onSave: function(event) {
    event.preventDefault();
    console.log("onSave handler called");
  },
  onCancel: function(event) {
   event.preventDefault();
   console.log("onCancel handler called");
  },
  render: function() {
    return (
      <form onSubmit={this.onSave}>
        <input type="text" />
        <button type="button" onClick={this.onCancel}>Cancel</button>
        <button type="submit">Save</button>
      </form>
    );
  }
});

Try it on Codepen.

This example satisfies our requirements. The enter key and the Save button both save the form. The Cancel button cancels the form. Rearranging the buttons won't break anything.

Plus, it's easy to read the code and determine what will happen without chasing multiple calls around:

  • When clicked, the Cancel button will call this.onCancel and nothing else.
  • Because the Save button is type="submit" and no click handler is registered, we know that clicking it will immediately trigger the form's onSubmit handler.
  • Because there are no type="submit" buttons with click handlers, we can be sure that pressing the enter key will immediately trigger the form's onSubmit handler.

Best Practices

Two best practices to take from this are always remember to add type="button" to non-submit buttons and only have one type="submit" button per form. That helps avoid ambiguity and makes following execution easy.

Here are some things not to do:

  • Don't re-order type="submit" elements to get the desired behavior. It's brittle and it will break immediately if someone or something reorders the elements on the page.
  • Don't decide not to implement predictable behavior for the enter key. This is bad UX and will frustrate some users, especially those who rely on the keyboard for accessibility reasons. And as you can see, it's easy once you know the rules.

Further Research

Codepens

Photo of React codepen Play around with multiple forms in the React Codepen

Building search is hard. Can we help? :)

tl;dr: I've joined Algolia as a developer advocate!

Josh Dzielak and Algolia Happy hour in the Paris office

Algolia helps developers build amazing search experiences inside of products and apps. Companies like Medium and ProductHunt use Algolia to deliver a super fast search-as-you-type experience. Popular developer tools like React, Scala and 100+ more use Algolia to make their documentation instantly searchable, all for free as part of Algolia's community program. The search box on this blog is powered by an Algolia-based project too.

I'm based in Paris but will also be in San Francisco and on the road, hopefully connecting to a Wi-Fi network near you. Drop me a line at my shiny new email address if you'd like to chat about integrations, open source projects, co-hosting events and all things search and API-related.

Hello Community! 🎉

I want to say a very special hello to Algolia developers, customers and supporters. It's a privilege to be working with you. Let's 🛠 stuff together.

Algolia Community Logo check out Algolia's rad community site

I look forward to getting to know you and learning about your ideas, projects and goals. What do you want to do and what can I do to help? Is there anything standing in your way? Don't hesitate to reach out and let me know, I'm here to 👂.

How to change the og:image tag on the wordpress.com free plan

The wordpress.com free plan doesn't give you control over which image becomes the og:image Open Graph meta tag on the pages and posts you've created. The tag is important because it's used to show a preview image for your page when it's shared on social networks like Facebook and Twitter. If the image is wrong it will confuse the people who want to share your page.

To see what the default preview image is for any Wordpress page or post you've created you can paste its URL into the Facebook debugging tool.

If the image isn't the one you want, there's a workaround to change it but stay on the free plan. Disclaimer: this workaround is based on trail and error from editing the Victorian Persistence blog's team page and could change at any time.

Photo of Estelle Murail I am not a Victorian scholar, but Estelle is!

The solution is to re-upload the image you want to be the og:image but make sure that its file name is alphabetically and numerically before any other images on the page. This is because the og:image selection works something like this: if you have two images IMG_1911.png and IMG_1916.png, the IMG_1911.png image will be chosen as the og:image because lexicographically IMG_1911.png is before IMG_1916.png.

If you want IMG_1916.png to become the og:image instead, re-upload it as IMG_1910.png, or with any file name that's lexicographically before IMG_1911.png. Then make sure to update the reference in the page/post to point to the new file. Publish your changes and then check the results with the Facebook debug tool.

This worked for me after trying many other strategies including changing image sizes, captions, order, CSS, etc. and I hope it will work for you. Let me know in the comments.

Search Presidential Speeches with Oval Quotes

Oval Quotes is a mashup I made using data from The Miller Center and search from Algolia. It's highly compact and lots of fun to play with.

Oval Quotes Screenshot

The app lets you search over 500 historical speeches by US presidents. You can search by full-text keywords, like gettysburg civil war, and you can filter results to one or more presidents. The results are delivered as quote-sized chunks that you can copy, paste and share.

Gettysburg Address on Oval Quotes

Because the search is powered by Algolia, Oval Quotes has a lot of nice features that didn't require me building them. Typo correction, highlighting search terms in results and faceting (filtering) are all handled automatically by the Algolia API and the instantsearch.js open source library. Check out this screencast to learn more about how Oval Quotes was built. The source code is up on Github.

Ready to try it out? Do know you how many presidents have mentioned shoes?

Evolving Work—Paris

» read on, or go directly to the slides

Recently I was asked to give a talk about startups to the prépa classes of St. Jean de Passy in Paris, France. These are top French students on the business school track. They're super sharp and it was a privilege to spend time with them.

Giving the presentation startup dress code ftw

I chose to talk about how startup teams are structured and why thoughtful organization design is becoming a big competitive advantage. I wanted the students to think about questions like: How can companies grow large without succumbing to bureaucracy? and What makes work fun?

The book Reinventing Organizations by Frederic Laloux deals with these sorts of questions and has become a big inspiration to me and my startup colleagues. Early chapters look at different ways that humans have organized throughout history. Later chapters make a compelling case for what lies ahead, including case studies of several modern-day Teal companies.

Teal company characteristics a slide about Teal characteristics

This presentation is my attempt to share some of the book's wisdom with St. Jean's students. Here's a link to the full slides.

Technical Note: The presentation was created using the excellent open source reveal.js HTML presentation framework. It works on desktop and mobile and supports direct linking to individual slides. The source code is on Github.