React: Button Dropdown

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

See the Pen React Dropdown by Tristan W (@tristaaan) on CodePen.

var Dropdown = React.createClass({
  getInitialState() {
    return { toggled: false };
  },
  componentDidUpdate: function(prevState) {
    if (this.state.toggled && !prevState.toggled) {
      window.addEventListener("click", this.handleClickOutside);
    } else if (!this.state.toggled && prevState.toggled) {
      window.removeEventListener("click", this.handleClickOutside);
    }
  },
  handleClickOutside: function(e) {
    var children = this.getDOMNode().getElementsByTagName("*");
    for (var x in children) {
      if (children[x] == e.target) {
        return;
      }
    }
    this.toggle();
  },
  toggle(e) {
    this.setState({ toggled: !this.state.toggled });
  },
  render() {
    var isHidden = !this.state.toggled ? "hidden" : "";
    return (
      <div className="dropdown">
        <button
          ref="dropdownButton"
          className="dropdown-button"
          onClick={this.toggle}
        >
          {this.props.buttonText}
        </button>
        <section
          ref="dropdownContent"
          className={isHidden + " dropdown-content"}
        >
          {this.props.children}
        </section>
      </div>
    );
  }
});

var Main = React.createClass({
  render() {
    return (
      <Dropdown buttonText="hello">
        <p>Goodbye</p>
      </Dropdown>
    );
  }
});

React.render(<Main />, document.getElementById("content"));

ReactJS: Change Color Simple Component

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

See the Pen React simple component by daryl (@darylw) on CodePen.

var green = '#39D1B4';
var yellow = '#FFD712';

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      color: green
    }
    
    this.changeColor = this.changeColor.bind(this);
  }
  
  changeColor() {
    let newColor = (this.state.color == green ? yellow : green);
    this.setState({ color: newColor });
  }
  
  render() {
    return (
      <div className="btn-block" style={{background: this.state.color}}>
        <h1 >
          Change my color
        </h1>
        <button className="btn" onClick={this.changeColor}>
          Change color
        </button>
      </div>
    );
  }  
}

ReactDOM.render(<Toggle />, document.getElementById('app'));

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