I want to create a form by using <input>
and <button>
like so:
I'm not sure how to pass the value I get from the text input field into a couple of functions on the frontend when I press the button "Send now". How do I make a <form onSubmit={}>
without using forms, rather just an input field and a button?
This is what I've tried so far and it's not working, I'm not sure how to get the input value and pass it into the function like this this.articleOnSubmit(*user input*)
. And also is the way i incorporated onChange={this.articleOnChange}
correct? Here is my code:
const Input = ({ placeholder, name, type, value }) => (
<input
placeholder={placeholder}
type={type}
step="0.0001"
value={value}
name={value}
/>
);
class Publish extends Component {
constructor(props) {
super(props);
this.state = {
articleTitle: '',
};
}
articleOnChange = (event) => {
let title = event.target.value;
this.setState({ articleTitle: title.toLowerCase() });
}
articleOnSubmit = (event) => {
if (this.state.articleTitle) {
console.log(this.state.articleTitle);
this.hash(this.state.articleTitle)
.then(hex => {console.log(hex); return hex;})
.then(hex => this.addArticleHash(hex));
event.preventDefault();
}
return (
<Input placeholder="Article Name" name="article" type="text" onChange={this.articleOnChange} />
<div/>
{false
? (<Loader />)
: (
<button
type="submit"
onClick={this.articleOnSubmit(Input.name)}
>
Send now
</button>
)}
</div>
);
}
CodePudding user response:
To make it work you have to fix 2 issues here:
- Since
Input
is a component, you have to get in its props theonChange
prop you pass to it, otherwise it won't work.
const Input = ({ placeholder, name, type, value, onChange }) => (
<input
onChange={onChange}
placeholder={placeholder}
type={type}
step="0.0001"
value={value}
name={value}
/>
);
- React
onClick
should be a function. Not a call. A function. What you did here wasonClick={this.articleOnSubmit(Input.name)}
- which is a call.
The solution is to change it into a function () => this.articleOnSubmit(Input.name)