Select placeholder with React

Here's how I created a 'placeholder' effect for an HTML select element in React.

The gist is that you create a react component that checks if a value has been set. If there is no value, a placeholder class is applied to the select element that will lighten the text color.

let React      = require('react');  
let classnames = require('classnames');

module.exports = React.createClass({

  render: function() {
    let value     = this.props.value;
    let onChange  = this.props.onChange;
    let className = classnames({
        'placeholder': !value
    });

    return (
      <select className={className} value={value} onChange={onChange}>
        <option value=''>Select...</option>
        <option value='1'>One</option>
        <option value='2'>Two</option>
      </select>
    );
  }

The above is a simple component that creates the specified options and includes an empty value option. When the empty value option is selected, the placeholder CSS class is applied to the select element.

The placeholder CSS looks like this...

select.placeholder {  
  color: #999;
}

That's all there is to it.

comments powered by Disqus