In this lab, you'll write forms, write and use controlled components, and write validation for form components.
Now that we know how to handle form elements in React and how to use controlled components, it's time to put that knowledge to the test. This lab is fairly extensive, but you'll use many core React concepts here that will surface again and again. Time to get some practice in!
General notes for this lab:
- Most of the DOM is pre-written for you in these exercises. Please do not remove anything that is already in the file — most of it is necessary to ensure that the tests run correctly.
- When instructed to save a value in the state, it doesn't matter what key you use, as long as it's in there!
- Open the
components/TwitterMessage.js
file. - This component takes one prop,
maxChars
, which is a number representing the maximum amount of characters a message can have. - You'll find an
<input type="text">
in this component. Make this a controlled component by adding the necessary props to the<input>
element. Its value should be saved in the component's state. - Show the remaining characters in the component. It doesn't matter how you render it, as long as the number is correct. No need to guard against input that is too long — you can let the counter reach negative values.
- Open the
components/LoginForm.js
file. - This component takes one prop,
onSubmit
, which is a function that gets called when the form is being submitted. - You'll find two inputs in this component:
<input type="text">
and<input type="password">
. Make this a controlled component by adding the necessary props to these inputs. Their values should be saved in the component's state. - An example of an input would look like:
<input id="test-username" type="text" name="username" value={this.state.username} onChange={this.handleInputChange} />
- Remember that you can retrieve the inpiut
name
andvalue
of anevent.target
from the JS event. - Add the necessary event handler to the
<form>
element in order to call theonSubmit
callback prop. - The
onSubmit
callback prop should only be called if both fields are filled in (with any value).
- Open the
components/PoemWriter.js
file. - You'll find one
<textarea>
in this component. Make this a controlled component. Recall that controlled components in React render dynamically based on some piece of props or state. Its value should be saved in the components state. - You'll also find an error element in the markup. This element should only be shown if the poem is not valid.
- The rules for a valid poem structure are as follows:
- The poem has three lines.
- The first line has five words.
- The second line has three words.
- The third line has five words.
- Be sure to account for users accidentally adding too many spaces! This means that
' I am a furry dog '
is not a valid first line of the poem. - Make sure the error message is still showing if the user deletes all of their content from the textarea box