git clone https://github.com/ross-u/02-react-props-intro.git
cd 02-react-props-intro
code .
npm i
-
state
is an object in reactclass
components used to save the data/state related to the current component. -
state
represents data that is private to every Reactclass
component itself.
// src/MyComponent.js
import React from 'react';
class MyComponent extends React.Component {
state = {
name: 'Sarah',
};
render() {
return (
<div>
<p> Hello {this.state.name}</p>
</div>
);
}
}
export default MyComponent;
// `state` represents data that is private to every class component itself
// ( it stores data that only component can access and change)
React components have ability to receive data from outside.
Meaning that we can pass / inject data to the components.
This is done by creating custom named attributes with the value (we are passing to) on each component element. This custom named attributes are called props
.
// src/App.js
import React from 'react';
import './App.css';
import MyComponent from './MyComponent';
class App extends React.Component {
render() {
return (
<div>
{/* city="Barcelona" is a prop ( data we pass to MyComponent ) */}
<MyComponent city="Barcelona" />
<MyComponent />
</div>
);
}
}
export default App;
// src/MyComponent.js
import React from 'react';
class MyComponent extends React.Component {
state = {
name: 'Sarah',
};
render() {
return (
<div>
<p> Hello {this.state.name}</p>
<p> Welcome to {this.props.city}</p>
{/*
props represent atributtes set on the component
and are used to pass data to the component from the outside
*/}
</div>
);
}
}
export default MyComponent;
Passing props
to a component - Image
Summary of using props
and state
- Image