load a new component on button click in ReactJs?
-
Hi, can you describe your problem more in deep? Maybe you can give some of your current state and what you want to achieveWesley Loh– Wesley Loh2020-05-06 17:15:42 +00:00Commented May 6, 2020 at 17:15
-
Please give me a solution added problem deeply @WesleyLohs saran– s saran2020-05-06 18:02:57 +00:00Commented May 6, 2020 at 18:02
Add a comment
|
2 Answers
I have fixed your code. Please check this example below:
MasterCreate Component
import MasterIncident from './MasterIncident';
import MasterAddPage from './MasterAddPage';
import React from "react";
class MasterCreate extends React.Component {
state = {
renderView: 0
};
clickBtn = (value) => {
this.setState({
renderView: value
});
};
render() {
switch (this.state.renderView) {
case 1:
return <MasterAddPage value={"Master Add Page is added"}/>;
default:
return <MasterIncident clickBtn={this.clickBtn}/>;
}
}
}
export default MasterCreate;
MasterIncident Component
import React from "react";
class MasterIncident extends React.Component {
render() {
console.log('master incident');
return (
<React.Fragment>
<button
variant="contained"
size="medium"
color="primary"
value="single"
name="1"
onClick={() => {this.props.clickBtn(0)}}
>
Add
</button>
<button
variant="contained"
size="medium"
color="primary"
value="batch"
name="2"
onClick={() => {this.props.clickBtn(1)}}
>
Export
</button>
<h3>Master Incident Inventory</h3>
</React.Fragment>
);
}
}
export default MasterIncident;
MasterAddPage Component
import React from "react";
const MasterAddPage = (props) => {
console.log(props);
return (
<div>Content</div>
)
};
export default MasterAddPage;
4 Comments
s saran
I tried this code but I facing this same error TypeError: Class constructor MasterIncident cannot be invoked without 'new'
Khabir
@ssaran, I have successfully run this code from my machine. Please create a simple component for showing "hello world" and check that whether it runs or not on your machine.
s saran
Another one help master Add page I have one close button if clicks go to Master incident page
Khabir
@ssaran, that means you want to go back when you click on close button. for going back , you need to use history and you can check this example and can implement this. stackoverflow.com/questions/61643881/…
instead of doing this?
render() {
switch (this.state.renderView) {
case 1:
return <MasterAddPage />;
default:
return <MasterIncident clickBtn={this.clickBtn} />;
}
}
you can do this:
render() {
return (
this.state.renderView === 0 ? <MasterAddPage /> : <MasterIncident clickBtn={this.clickBtn} />
)
}