ReactJS: Radio button and show selected

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

See the Pen React Radio Buttons by Nick Van Dyck (@nickvdyck) on CodePen.

const RadioGroup = ({ name, value, children, onChange, ...rest }) => {
  const checked = typeof onChange === "function" ? "checked" : "defaultChecked";
  return (
    <div onChange={onChange}>
      {children.map(child =>
        React.cloneElement(child, {
          [checked]: child.props.value === value,
          name,
          ...rest
        })
      )}
    </div>
  );
};

const RadioButton = ({ label, value, className, ...rest }) => (
  <label className={className}>
    <input type="radio" value={value} {...rest} />
    {label}
  </label>
);

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: "",
      fruits: ["Grape", "Apple"]
    };

    this.resetSelection = this.resetSelection.bind(this);
    this.changeFruit = this.changeFruit.bind(this);
    this.showSelected = this.showSelected.bind(this);
  }

  showSelected() {
    alert(`Current selection: ${this.state.selected || "none"}`);
  }

  changeFruit(event) {
    this.setState({ selected: event.target.value });
  }

  resetSelection() {
    this.setState({ selected: "" });
  }

  render() {
    return (
      <div>
        <RadioGroup
          name="fruit"
          onChange={this.changeFruit}
          value={this.state.selected}
        >
          {this.state.fruits.map(fruit => (
            <RadioButton value={fruit.toLowerCase()} label={fruit} />
          ))}
        </RadioGroup>
        <br />
        <button onClick={this.resetSelection}>Reset Selection</button>
        <button onClick={this.showSelected}> Show Selected </button>
      </div>
    );
  }
}

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

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')
);