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