React Two

Working with Props

Data Flow Recap

Data in React flows unidirectionally, from the top of the component tree to the bottom. Using props allows us to pass data from component to component, while events can work up the component tree.

Passing Props

When passing props from component to component, we pass them directly into the components tag.

import React from 'react';
import ChildComponent from './ChildComponent';

class ParentComponent extends Component {
    constructor(){
        super();

        this.state = {
            name: 'Tayte'
        }
    }

    render(){
        return (
            <div>
                <ChildComponent myName={this.state.name}/>
            </div>
        )
    }
}

export default ParentComponent

Import child component

Prop name

Prop value

Receiving Props: Functional

Receiving Props is different depending on whether the component receiving props is a class or functional component. Accessing props from a functional component looks like this:

import React from 'react';

const ChildComponent = (props) => {
    return (
        <h1>My name is: {props.myName}</h1>
    )
};

export default ChildComponent;

Props parameter

Access the value from the props object

Receiving Props: Class

When receiving props in a class component we need to utilize context. Note that the context of 'this' in a class component is the component itself.

import React, {Component} from 'react';

class ChildComponent extends Component {
    render(){
        return (
            <h1>My name is: {this.props.myName}
        )
    }
}

export default ChildComponent;

Access the value from the props object, and use context

Passing Methods

When passing methods as props, we need to bind the method to its component so it maintains the proper context. Once bound, the method an be passed like any other prop.

    constructor(){
        super();

        this.state = {
            name: 'Matt'
        }

        this.changeName = this.changeName.bind(this);
    }

    changeName(){
        this.setState({
            name: 'Tayte V2'
        })
    }

bind methods here in the constructor

Passing Methods

render(){
  return (
    <div>
      <ChildComponent 
        myName={this.state.name} 
        changeName={this.changeName}/>
    </div>
  )
}

class ChildComponent extends Component {
  render(){
    return (
      <div>
        <h1>My name is: {this.props.myName}</h1>
          <button onClick={this.props.changeName}>Update Name</button>
      </div>
    )
  }
}

export default ChildComponent;

pass the method as a prop

using method prop in event

React 2

By matias_perez

React 2

Props and Binding

  • 190