I have a form in one of my React components, and and in the outside component that calls it I want to pass a reference to a button there, so that I can also submit that usin
Edit: Simple and correct answer: https://stackoverflow.com/a/53573760/5271656
In React, data flows down and actions flow up. So notify child component about button click in the parent.
This is how you can do this.
import React, { Component } from "react";
import ReactDOM from "react-dom";
class CustomForm extends Component {
handleOnSubmit = e => {
e.preventDefault();
// pass form data
// get it from state
const formData = {};
this.finallySubmit(formData);
};
finallySubmit = formData => {
alert("Form submitted!");
};
componentDidUpdate(prevProps, prevState) {
if (this.props.submitFromOutside) {
// pass form data
// get it from state
const formData = {};
this.finallySubmit();
}
}
render() {
return (
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
submitFromOutside: false
};
}
submitCustomForm = () => {
this.setState({
submitFromOutside: true
});
};
componentDidMount() {
console.log(this.form);
}
render() {
return (
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render( , rootElement);
To me, this solution is hacky and not in a react way but serves your use-case.
Find working solution here:https://codesandbox.io/s/r52xll420m