0

I want to create a form by using <input> and <button> like so:

enter image description here

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>
 );
  
}

1 Answer 1

1

To make it work you have to fix 2 issues here:

  1. Since Input is a component, you have to get in its props the onChange 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}
  />
);
  1. React onClick should be a function. Not a call. A function. What you did here was onClick={this.articleOnSubmit(Input.name)} - which is a call.

The solution is to change it into a function () => this.articleOnSubmit(Input.name)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.