score:2
Accepted answer
i could write you a bunch of theories, facts, and opinion-based statements.
instead of that, i've chosen to write down the code. look at the comments for more insight into the workflow, and if you have any questions, i'll be here to provide help.
run the code snippet and see ti in action.
class formcomponent extends react.component {
constructor(props) {
super(props);
this.state = {name: '', age: null, submitted: false}; // here we're saving our input values
}
// let's handle the input changes
// this is a great approach, since we don't need to write multiple 'onchange' handlers.
// depending on what's the current 'name' of the input, we're assigning the currently entered value.
// we're accessing it via the 'e' -event parameter that's automatically passed to us
handlechange = (e) => {
this.setstate({[e.target.name]: e.target.value});
}
// this is our onsubmit handler
handlesubmit = (e) => { // same e parameter
const { name, age, submitted } = this.state; // here we're doing a bit od es6 destructuring
// instead of showing that 'alert' we'll change the 'submitted' part of the state to true. this check is going to be useful when we come to the part where we want to check if the user has clicked the button if yes, this part will be equal to true and we'll show them the output if not, nothing will be shown.
// alert(`your name is ${name} and you're ${age} years old`);
this.setstate({ submitted: true });
e.preventdefault();
}
render() {
// here we're doing that destructuring again.
// so, later on we can use e.g. 'name' inseatd of 'this.state.name'
const { name, age, submitted } = this.state;
return (
<div>
<form onsubmit={this.handlesubmit}>
<label>
name:{' '}
<input
/* this the above used 'name' property -> e.target.name */
name='name'
type="text"
/* setting the current value from the current
state value and making this into a controlled
form which is what we want 99% of the time */
value={this.state.name}
/* here we are passing in a reference to our
'handlechange' functions to the built-in
'onchange' method */
onchange={this.handlechange}
required />
</label>
<br />
<br />
<label>
age:{' '}
<input name="age"
type="number"
value={this.state.age}
onchange={this.handlechange}
required />
</label>
<br />
<br />
<input type="submit" value="submit" />
</form>
<br />
{/* here will be our output. what we're doing here is checking if the form was submitted.
//if that's true then we want to show our newly created string, but if not, we don't want to show anything in that case -> 'null' */}
{submitted ? <p>{`your name is ${name} and you are ${age} years old.`}</p> : null}
</div>
);
}
}
reactdom.render(
<formcomponent />,
document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Source: stackoverflow.com
Related Query
- Retrieve form input and use it within a string
- Take input value from submit form and store in redux store to use later
- How to use object values and retrieve it in antd form
- I want to use useEffect once i submit a form and take the value from input field and assign it to a api url and get response
- Title and event form input not posted and retrieve using Reactjs
- Clear and reset form input fields
- Facing issue while adding radio button in react - input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`
- Reactjs Warning: input is a void element tag and must not have `children` or use `props.dangerouslySetInnerHTML`. Check the render method of null
- Is the use of the <form> tag necessary in ReactJS that have HOC input tags that handle form-esque events and behaviour?
- Can someone give proper explanation for ref vs controlled input and use case for state variable in react?
- How to avoid very long paths and use absolute paths within a Create React App project?
- Error: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`
- how to properly use the async and await keywords within a map
- How to use UTC date string as recharts axis and distribute it evenly
- React / Javascript - Remove white spaces from both ends of a string and extra spaces between words, from a input field (search bar)
- Dynamic form returns the same value for the first and second input
- Redux Form - Return current input value as string onChange
- Customize Antd AutoComplete to use {children} for both dataSource and input
- How to take input value from submit form and store in redux store variable?
- Get value from input and use on the button
- How do I get my HTML form date input to only allow specific days of the week to be chosen using JavaScript, React and HTML?
- REACT: What I should write in propTypes when in form I use input type="file'?
- How leetcode do this: Read user's input String as multiple JavaScript functions and run a main function with user's input params
- In React Hooks. How to set state to a random number and use that to display a string from an array
- Can you use jsx within template string in React render props?
- Facebook React.js :: how to create form input field and set type, autofocus, required etc
- Uncontrolled Input to Controlled Input Warning in React Hook Form and Material UI's TextField
- Use serverless function to findById in MongoDB Database via Mongoose, and render result in React form - not working
- How to retrieve string after @ character and before space using javascript or react?
- Handle multiple react form input and update the state of the component
More Query from same tag
- How can I filter and map over an array at the same time?
- How to fetch from another API after useState has finished setting the value
- Press Enter button and filter data
- Bottom navigation disappears when route clicked
- How to open React Material-UI modal and populate with Ajax call upon clicking button?
- React setInterval in UseEffect not updating correctly in background tab
- Passing parameters to a class component in REACT Expo
- Destructuring an object with useState
- Nested forms with global state
- How to pass props to React Big Calendar from custom event?
- React JS Filter Methods: Hiding table columns using array filters and state
- useEffect within a custom hook doesn't rerender on delete
- How do I make it so that the React router shows multiple elements when routing to the same address?
- How to add a Loading Animation when a Button is Clicked?
- django , react , redux authentication token is null
- Uncaught Invariant Violation : Maximum update depth exceeded
- Render React Component from name inside array map
- CORS issue on Localhost, MULTIPLE workarounds have failed
- AWS S3 File Download from the client-side
- Can't setup nginx proxy to docker container with react
- I try to parse my data with props between react components but I get undefined values
- useState not working inside a custom react hook
- How do you encode a file to base64 then upload as multipart file to backend api using JS?
- Wrapping a high order component(HOC) around a React component in JSX
- How to make useEffect only run once on component mount without lying to React?
- Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead
- How do I map an array of objects with react
- How to style the cell edit component in material table?
- Eslint error when I use babel alias on nextjs
- Disable type checking from all .tsx files