Types of React Components
Two types of React components
- a stateful component: has a state property
- a stateless component: does not have a state property
A component can change its state by calling
this.setState()
but a component should never updatethis.props
Use props
to store information that can be changed, but can only be changed by a different component.
Use state
to store information that the component itself can change.
Build a Stateful Component Class
Passing information from a stateful component to a stateless component using class
- Create a component class with state
class Parent extends React.Component{
constructor(props){
super(props);
this.state= {
name: 'Penny'
};
}
2. In another file, create another component class (with no state) but passing in a prop from Parent component called name
class Child extends React.Component{
render(){
return <h1>Hey, my name is {this.props.name}!</h1>;
}
}
3. Rendering is the only way for a component to pass props
to another component using export
export class Child extends React.Component{
render(){
return <h1>Hey, my name is {this.props.name}!</h1>;
}
}
4. Import an exported component from another file and import its prop in the render method. Give the Child attribute a name name
import { Child } from './Child';render() {
return <Child name={this.state.name} />;
}
}