score:0

Accepted answer

pass a function from a parent component to you child component (the form):

https://codesandbox.io/s/4x3zjwxwkw

const app = () => (
  <div>
    <createrecipe />
    <updaterecipe />
  </div>
);

class createrecipe extends react.component {
  constructor(props) {
    super(props);
    this.onsubmit = this.onsubmit.bind(this);
  }
  onsubmit(e) {
    e.preventdefault();
    console.log("do post recipe");
  }
  render() {
    return (
      <div>
        <myform title="post recipe" onsubmit={this.onsubmit} />
      </div>
    );
  }
}

class updaterecipe extends react.component {
  constructor(props) {
    super(props);
    this.onsubmit = this.onsubmit.bind(this);
  }
  onsubmit(e) {
    e.preventdefault();
    console.log("do get recipe");
  }
  render() {
    return (
      <div>
        <myform title="get recipe" onsubmit={this.onsubmit} />
      </div>
    );
  }
}

const myform = ({ title, onsubmit }) => {
  return (
    <div>
      <h2>{title}</h2>
      <form onsubmit={onsubmit}>
        <input type="text" />
        <button type="submit">submit</button>
      </form>
    </div>
  );
};

edit: per the comment, you can absolutely separate the post and get submit functions, but this duplicates logic a bit. what could be better is to have the <app /> component own the two submit functions, and pass them respectively to <updaterecipe /> and <postrecipe />, maybe even the titles too! i'll let you compose this however you'd like, but hopefully this shows you the flexibility of react.

score:0

you can pass in a method as a prop to the component - that way you can define the functionality outside of the component and let it execute it within the components scope.

an example of this would be passing in a onpress event to a button, or an onclick event to any other component.

score:0

you can pass the method into the component as a prop and then reference props in your submit function like this:

submit = () => {
     var data = {
        method: this.props.method,
        ...
     };

   fetch('/url/', data);
}

Related Query

More Query from same tag