Michael J. Stokes | Learning React ES6: Creating Forms and Submitting Data


Today’s lesson I’ve learned how to create a form in React ES6. I know how forms are created in HTML but doing in JSX is way different.

I only created just a one button simple submit form. Here’s how it’s done in JSX:

Create a template

const template = (
<div>
<form>
<input type="text">
<button>Submit</button>
</form>
</div>
);

The form needs some kind of action to be submitted. The action attribute is not used for this, but in order to submit a form in JSX, I use the following attribute:

<form onSubmit=''>

Now I had to create a JavaScript code to make it work

const onFormSubmit = (e) => {
  e.preventDefault();
};

To make JavaScript to work in HTML elements in JSX, I need to wrap the name of the function in curly braces like this:

<form onSubmit={onFormSubmit}>

Now here is a clear example of a form created in JSX and rendered in React ES6:

const onFormSubmit = (e) => {
	e.preventDefault();
const option = e.target.elements.option.value;
};




const appRoot = document.getElementById('app');



const render = () => {
	const template = (

	<div>
		<h1>{app.title}</h1>
		{app.subtitle && <p>{app.subtitle}</p>}
		<p>{app.options.length > 0 ? 'Here are your options' : 'No options'}</p>
		<p>{app.options.length}</p>
		<button onClick={removeAll}>Remove All</button>

		<ol>
			<li>Item One</li>
			<li>Item Two</li>
		</ol>
		<form onSubmit={onFormSubmit}>
			<input type="text" name="option"/>
			<button>Add Option</button>

		</form>	
	</div>

	);

	ReactDOM.render(template, appRoot);

};


render();

Creating forms in React can be challenging but it’s gets better and exciting once you master your JavaScript skill set. Happy coding!



No Comments Yet

You can be the first to comment!


Leave a Comment






Previous Post : « | Next Post : »