Select Page

From Codecademy. A basic example of the relationship between parent and child components.

https://snippets.cacher.io/snippet/9fbadaa1cfce6e939c74

App Functionality

App displays “Hey, my name is Frarthur.”

App parts

We only worked on Random.js and its child component Button.js
Other components in the project are Parent.compiled.js ; index.html ; styles.css

Functionality and connectedness of app parts

Parent.js imports { Child } from ‘./Child’
Parent.js consists of a class component Parent, and a ReactDom.render
Parent.js renders Child, passing it a props name={this.state.name}
Child.js renders <h1>Hey, my name is {this.props.name}</h1>

Parent 

The class Parent has two methods:
constructor(props) that sets state like so: this.state={ name: ‘Frarthur’ };

render() that returns the Child component, and passes it the props name={this.state.name}

Child

The class Child has only a render() method that returns <h1>Hey, my name is {this.props.name}</h1>;

Note that Child receives the name attribute from Parent via props, and that parent sets the state of the name in state.

Notes from Codecademy on this app:

Since Parent is supposed to be stateful, it will need to set its initial state. That means that it will need a constructor method.

Child is going to receive a prop called name, and display that prop on the screen.

How can you make a component display a prop called name?

  • To access a prop, use the expression this.props.name-of-prop.

  • To make a component display something, include that thing in the render function’s return statement.

You need to include this.props.name inside of Child‘s render function’s returnstatement.

In this app, Rendering <Parent /> will render both components, because Parent‘s render function returns a <Child />. Click Run, and see the rendered information that you passed down from Parent.

Don’t update props

A React component should use props to store information that can be changed, but can only be changed by a different component.

A React component should use state to store information that the component itself can change.

Bad:

class Bad extends React.Component {
render() {
this.props.message = ‘yo’; // NOOOOOOOOOOOOOO!!!
return<h1>{this.props.message}</h1>;
}
}