Answers for "react passing state as props"

0

react passing state as props

REACT passing State as a prop to child component

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Tony Stark'
    }
  }
  render() {
    return (
       <div>
      	/* Pass State as a prop by adding a property and giving it a value from this.state */
         <ChildComponent name={this.state.name}/>
       </div>
    );
  }
};

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
    <div>
      /* The prop of name is now accessed with this.props */
      <h1>Hello, my name is: {this.props.name}</h1>
    </div>
    );
  }
};
Posted by: Guest on July-15-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language