bradxr
12/13/2018 - 11:27 AM

04 - Working with Props

Working with Props

  • props is a special object that is passed to components by default
  • props are accessed differently in stateful and stateless components
  • in stateful, use {this.props.name}
  • in stateless, use {props.name}
  • a special prop, children allows us to access any element between the opening and closing tags of a component

In Main Component

Code Example

import React, {Component} from 'react';

class App extends Component {
  render() {
    return (
      <div>
        // passing attributes (i.e. props) to the person component
        <Person name="Brad" age="22" />
        // passing data between the opening and closing tags of a component i.e. children
        <Person name="Eleanor" age="21">My hobbies include make-up and animals</Person>
      </div>
    );
  }
}
export default App;

In Secondary Component

  • secondary component will output:
    • 1st person component: "Hi! Im Brad and Im 22 years old"
    • 2nd person component: "Hi! Im Eleanor and Im 21 years old" "My hobbies involve make-up and animals"
  • if no props.children exists then no output will render for that paragraph

Code Example

import React from 'react';

const person = (props) => {
  return (
    <p>Hi! Im {props.name} and Im {props.age} years old</p>
    <p>{props.children}</p>
  );
}
export default App;