Reputation: 156
I would like to split my render into several parts.
There must be some code bits missing because my real code is more than a thousand lines, this one is for example.
Basically I would like to be able to call Page2
and use the functions handleSubmit
and handleChange
in the Page2
. But when i'm calling Page2, the code say he don't find the handleSubmit and the handleChange. I would like it to work as if I had not separated my code into several functions. If anyone have a idea :/
So I separated my code like this:
Page1.js :
import {Page2} from './Page2';
const initialState = { test:'', test2: ''};
export default class Page1 extends Component {
constructor(props) {
super(props);
this.state = initialState;
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const InputValue = event.target.value;
const stateField = event.target.name;
this.setState({
[stateField]: InputValue,
});
console.log(this.state);
}
async handleSubmit(event) {
this.setState({ loading: true });
event.preventDefault();
const { test= ''} = this.state;
await axios.post(' (endpoint API)',
{ key1: `${test}`);
}
render() {
return (
<Tabs selectedIndex={this.state.tabIndex} onSelect={tabIndex => this.setState({ tabIndex })}>
<TabList>
<Tab >Non Dynamique</Tab>
<Tab> Automation </Tab>
</TabList>
<TabPanel>
<Input type="number" step="0.01" name="test" onChange={this.handleChange} value=
{this.state.test || ''}/> </Col>
<Button type="submit"> Update </Button>
</TabPanel>
<TabPanel>
{this.Page2}
</TabPanel>
);
}
}
Page 2:
export class Page2 extends Component {
render() {
return(
<Input type="number" step="0.01" name="test2" onChange={this.handleChange} value=
{this.state.test || ''}/> </Col>
<Button type="submit"> Update </Button>
);
}
}
Thank you for any response
Upvotes: 0
Views: 2944
Reputation: 1481
you need to render page2
as react component and pass those function reference as props something like this.
<Page2 handleChange={this.handleChange} handleSubmit={this.handleSubmit} />
In Page2 component you can get the above function reference in props.
export default class Page2 extends React.Component {
constructor(props) {
super(props);
this.state= {
}
}
render() {
const { handleSubmit, handleChange} = this.props
return(
<div>
<Input type="number" step="0.01" name="test2" onChange={handleChange} value=
{this.state.test || ''}/>
<Button type="submit" onSumbit={handleSubmit}> Update </Button>
</div>
)
}
}
Upvotes: 3
Reputation: 2135
<Page2 handleChange={this.handleChange} handleSubmit={this.handleSubmit} test={this.state.test}/>
On Page2 code
export default render2 = (props) => {
return <div>
<Input type="number" step="0.01" name="test2" onChange={props.handleChange} value=
{props.test || ''}/> </Col>
<Button type="submit" handleSubmit={props.handleSubmit}> Update </Button>
</div>
};
Upvotes: 0