ReactJS: Radio button

This entry is part 30 of 35 in the series React JS

See the Pen React Radio Button Component by Sandy Gifford (@SandoCalrissian) on CodePen.

interface IRadioButtonsProps {
	buttons: string[];
	selected?: string;
	onChange?: (value: string) => void;
}
interface IRadioButtonsState { }

class RadioButtons extends React.Component<IRadioButtonsProps, IRadioButtonsState> {
	private static count = 0;
	private id: number;
	private groupName: string;

	constructor(props: IRadioButtonsProps) {
		super(props);

		this.id = RadioButtons.count;
		RadioButtons.count++;

		this.groupName = `RadioButtons__${this.id}`;
	}

	public render(): React.ReactElement<any> {
		return (
			<div className="RadioButtons">
				{this.props.buttons.map((value, index) => {
					const inputID = `${this.groupName}__${index}`;
					return (
						<div key={index} className="RadioButtons__group">
							<input
								className="RadioButtons__group__input"
								type="radio"
								name={this.groupName}
								id={inputID}
								checked={this.props.selected === value}
								onChange={() => this.props.onChange(value)} />
							<label
								className="RadioButtons__group__label"
								htmlFor={inputID}>{value}</label>
						</div>
					);
				})}
			</div>
		);
	}
};

interface IAppProps { }
interface IAppState {
	selected: string;
}

class App extends React.Component<IAppProps, IAppState> {
	constructor(props: IAppProps) {
		super(props);

		this.state = {
			selected: "Option 1",
		};
	}

	public render(): React.ReactElement<any> {
		return (
			<div className="App">
				<RadioButtons
					buttons={["Option 1", "Option 2", "Option 3"]}
					selected={this.state.selected}
					onChange={(value) => {
						this.setState({
							selected: value,
						});
					}} />
			</div>
		);
	}
};

ReactDOM.render(<App />, document.getElementById("ReactWrapper"));

ReactJS: How to define a required textfield

This entry is part 29 of 35 in the series React JS

See the Pen React – Textfield by daryl (@darylw) on CodePen.

class Textfield extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {value: this.props.value};
  }
 	
  render() {
    const {
			label,
			mandatory=false,
			readOnly=false,
			errorMessage=''} = this.props;
		
		return (
      <div>
				<Label>{label}</Label>
        <input className="textInput" value={this.state.value} type="text" onChange={this.handleChange} readOnly={readOnly} />
       	{this.state.value == '' && mandatory ?
					<ErrorMessage>{errorMessage}</ErrorMessage>
				: null
				}
      </div>
    )
  }
  
  handleChange(e) {
		this.setState({value: e.target.value});
	}
}

const Label = ({children}) => (
	<label className="formLabel">{children}</label>
)

const ErrorMessage = ({children}) => (
	<span className="errorMessage">{children}</span>
)

var formDefinition = {
	formName: "My Form",
	formVersion: "1.0",
	formItems: [
		{
			mandatory: true,
			errorMessage: "Your name is required",
			label: "What is your name?"
		},
		{
			mandatory: true,
			errorMessage: "Your age is required",
			label: "What is your age?"
		}
	]
}

class Form extends React.Component {
	constructor(props) {
		super(props);
	}
	
	render() {
		let formItems = [];
		this.props.formDef.formItems.forEach((formItem) => {
			formItems.push(<Textfield mandatory={formItem.mandatory} errorMessage={formItem.errorMessage} label={formItem.label}/>)
		});
		
		return (
			<div>
				{formItems}
			</div>
		)
	}
}

ReactDOM.render(
	<div>
		<Form formDef={formDefinition}/>
	</div>
	, document.getElementById('root'));

ReactJS: Dropdown with no windows listener

This entry is part 28 of 35 in the series React JS

See the Pen React Dropdown – No Window Listener by daryl (@darylw) on CodePen.0

class Dropdown extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      expanded: false,
      value: "Donuts"
    };
  }

  expand() {
    this.setState({ expanded: true });
  }

  collapse() {
    this.setState({ expanded: false });
  }

  handleItemClick(e) {
    this.setState({
      expanded: false,
      value: e.target.innerText
    });
  }

  handleTriggerClick() {
    this.setState({ expanded: !this.state.expanded });
  }

  render() {
    let dropdown = undefined;
    if (this.state.expanded) {
      dropdown = (
        <div className="content">
          {this.props.options.map(item => {
            return (
              <div
                onClick={e => {
                  this.handleItemClick(e);
                }}
                className="item"
              >
                {item}
              </div>
            );
          })}
        </div>
      );
    }

    return (
      <div
        className={'dropdown ${this.state.expanded ? "active" : ""}'}
        tabIndex="0"
        onBlur={() => {
          this.collapse();
        }}
      >
        <div
          className="trigger"
          onClick={() => {
            this.handleTriggerClick();
          }}
        >
          {this.state.value}
        </div>
        {dropdown}
      </div>
    );
  }
}

ReactDOM.render(
  <Dropdown
    options={["Strawberry Cream", "Chocolate Flakes", "Marshmallow Sprinkles"]}
  />,
  document.getElementById("app")
);

ReactJS: Dropdown

This entry is part 27 of 35 in the series React JS

See the Pen React Dropdown by daryl (@darylw) on CodePen.0

class DropdownItem extends React.Component{
  render() {
    return (<li className="dropdown-option" 
              onClick={this.props.click}>
                {this.props.label}
          </li>);
  }
}

class DropdownMenu extends React.Component {
  render() {
    let className="dropdown-select";
    if (this.props.toggled) {
      className += " open";
    }
    
    return <ul className={className}>
          {this.props.children}
        </ul>
  }
}

class Dropdown extends React.Component {
  constructor (){
    super();
    
    this.state = {
      toggled: false,
      selected: "Default"
    };
  }
  
  toggleDropdown () {
    this.setState({toggled: !this.state.toggled});
  }

  handleClick(value) {
    this.setState({selected: value});
    
    this.closeDropdown();
  }

  render () {
    var className="dropdown-container";
    
    if (this.props.className) {
      className += " " + this.props.className;
    }

    var dropdown = React.Children.map(
      this.props.children, (child, i) => {
      
      var clonedProps = {};
      clonedProps.click = this.handleClick.bind(this, i);

      return React.cloneElement(child, clonedProps);
    });

    return (
      <div className={className} 
        onClick={this.toggleDropdown.bind(this)}>
        <div className="dropdown-label">
          {this.props.label}
        </div>
        <div className="dropdown-active">
          {this.props.children[this.state.selected]}
        </div>
        <DropdownMenu toggled={this.state.toggled} >
          {dropdown}
        </DropdownMenu>
      </div>
    );
  }
}

React.render(
    <Dropdown label="Dropdown Label">
      <DropdownItem label="Choice 1" value="Number 1" />
      <DropdownItem label="Choice 2" value="2" />
    </Dropdown>,
  document.getElementById('app')
);

ReactJS: Checkbox

This entry is part 26 of 35 in the series React JS

See the Pen Stateful React checkbox component by daryl (@darylw) on CodePen.0

/**
* www.devhamsters.com
*/

class Checkbox extends React.Component {
  static propTypes = {
    checked: React.PropTypes.bool,
    disabled: React.PropTypes.bool,
  };
  static defaultProps = {
    checked: false,
    disabled: false,
  };
  constructor(props) {
    super(props);
    this.state = {
      checked: props.checked,
    };
  };

  _handleChange = () => {
    this.setState({
      checked: !this.state.checked,
    });
  };

  render() {
    const { disabled } = this.props;
    const { checked } = this.state;
    return (
      <div className="React__checkbox">
        <label>
          <input 
            type="checkbox"
            className="React__checkbox--input"
            checked={checked}
            disabled={disabled}
            onChange={this._handleChange}
          />
          <span 
            className="React__checkbox--span"
          />
        </label>
      </div>
    );
  }
}

const App = (
  <div className="App">
    <Checkbox />
    <Checkbox checked />
    <Checkbox disabled />
    <Checkbox checked disabled />
  </div>
);
      
ReactDOM.render(
  App, 
  document.getElementById('app')
);