Functions or classes that manage and return React elements.
Accept a single props
argument and return a React element.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>
}
Extend
React.Component
and implement a render()
method that returns a React element.
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>
}
}
React uses an instance of the component's class per component
lifecycle,
calling its render()
method when a state update is needed
(as long as we render <Welcome />
into the same DOM node, only a single instance of the Welcome
class will be used).
Note
One important difference is that class components have class instances, while function components don't.
React components can be represented by tags.
const element = <Welcome name='Sara' />
React translates this JSX to a Welcome
function call with a { name: 'Sara' }
argment as props
,
or to an instance of the Welcome
class initialized with that props
.
Always start component names with a capital letter.
Components can refer to other components.
function App() {
return (
<div>
<Welcome name='Sara' />
<Welcome name='Cahal' />
<Welcome name='Edite' />
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
Consider:
const Comment = props => (
<div className='Comment'>
<div className='UserInfo'>
<img className='Avatar'
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className='UserInfo-name'>
{props.author.name}
</div>
</div>
<div className='Comment-text'>
{props.text}
</div>
<div className='Comment-date'>
{formatDate(props.date)}
</div>
</div>
)
Now extract a Avatar
and a UserInfo
components:
const Avatar = props => (
<img className='Avatar'
src={props.user.avatarUrl}
alt={props.user.name}
/>
)
const UserInfo = props => (
<div className='UserInfo'>
<Avatar user={props.user} />
<div className='UserInfo-name'>
{props.user.name}
</div>
</div>
)
This lets us simplify Comment
:
const Comment = props => (
<div className='Comment'>
<UserInfo user={props.author} />
<div className='Comment-text'>
{props.text}
</div>
<div className='Comment-date'>
{formatDate(props.date)}
</div>
</div>
)
- Props are Read-Only!