1function LoginForm() {
2 const [form, setState] = useState({
3 username: '',
4 password: ''
5 });
6
7 const printValues = e => {
8 e.preventDefault();
9 console.log(form.username, form.password);
10 };
11
12 const updateField = e => {
13 setState({
14 ...form,
15 [e.target.name]: e.target.value
16 });
17 };
18
19 return (
20 <form onSubmit={printValues}>
21 <label>
22 Username:
23 <input
24 value={form.username}
25 name="username"
26 onChange={updateField}
27 />
28 </label>
29 <br />
30 <label>
31 Password:
32 <input
33 value={form.password}
34 name="password"
35 type="password"
36 onChange={updateField}
37 />
38 </label>
39 <br />
40 <button>Submit</button>
41 </form>
42 );
43}
1// First: import useState. It's a named export from 'react'
2// Or we could skip this step, and write React.useState
3import React, { useState } from 'react';
4import ReactDOM from 'react-dom';
5
6// This component expects 2 props:
7// text - the text to display
8// maxLength - how many characters to show before "read more"
9function LessText({ text, maxLength }) {
10 // Create a piece of state, and initialize it to `true`
11 // `hidden` will hold the current value of the state,
12 // and `setHidden` will let us change it
13 const [hidden, setHidden] = useState(true);
14
15 // If the text is short enough, just render it
16 if (text.length <= maxLength) {
17 return <span>{text}</span>;
18 }
19
20 // Render the text (shortened or full-length) followed by
21 // a link to expand/collapse it.
22 // When a link is clicked, update the value of `hidden`,
23 // which will trigger a re-render
24 return (
25 <span>
26 {hidden ? `${text.substr(0, maxLength).trim()} ...` : text}
27 {hidden ? (
28 <a onClick={() => setHidden(false)}> read more</a>
29 ) : (
30 <a onClick={() => setHidden(true)}> read less</a>
31 )}
32 </span>
33 );
34}
35
36ReactDOM.render(
37 <LessText
38 text={`Focused, hard work is the real key
39 to success. Keep your eyes on the goal,
40 and just keep taking the next step
41 towards completing it.`}
42 maxLength={35}
43 />,
44 document.querySelector('#root')
45);