Question
This is involving javascript using react. The problem is to pass 2 variables of data from...
This is involving javascript using react. The problem is to pass 2 variables of data from a parent component to a child component. Pass these two variables to the child component: user1 = "[email protected]", user2 = "[email protected]".
-----------------Parent.js-----------------
import React from "react";
import ReactDOM from "react-dom";
import GuestApp from "./GuestApp";
class App extends React.Component {
constructor(props) {
super(props); // Must call
this.state = {role: "admin"};
}
render() {
switch (this.state.role) {
case 'guest':
return <GuestApp /* Insert the passing data in here */ />;
break;
}
}
}
ReactDOM.render(<App />, document.getElementById("root"));
-----------------Child.js-----------------
import React from "react";
class GuestApp extends React.Component
{
constructor(props)
{
super(props); // Must call
this.state = {show: "home"};
}
render()
{
/* Insert any code here as needed to accept the passed down information from parent.js */
}
}
Modify the parent and child files as needed to pass down the information from parent to child. Need not worry about any component rendering or anything else. This exercise is only to correctly pass information down.
Answers
We can do this in multiple ways but here I have passed it down as a prop and the used it using object destructuring. My code is below.
This is the parent component
import React from "react";import ReactDOM from "react-dom";import GuestApp from "./GuestApp";class App extends React.Component {constructor(props) {super(props); // Must callthis.state = { role: "admin" };}render() {switch (this.state.role) {case "guest":return (<GuestApp/* Insert the passing data in here *//>);break;}}}ReactDOM.render(<App />, document.getElementById("root"));This is the child component.
import React from "react";class GuestApp extends React.Component {constructor(props) {super(props); // Must callthis.state = { show: "home" };}render() {/* Insert any code here as needed to accept the passed down information from parent.js */const { user1, user2 } = this.props;}}I hope you liked it.