id | sidebar_label | title | description | keywords | version | image | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
stateless-function |
Stateless function |
Stateless Function (Presentational Component) |
Stateless function (Presentational component) | React Patterns, techniques, tips and tricks in development for React developers. |
|
Stateless function (Presentational component) |
/img/reactpatterns-cover.png |
- Stateless function is a way to define React components as a function. Rather than as a class or via
React.createClass
. - Stateless function does not hold state; just props.
Without stateless function, write a presentational component that is just renders props, and doesn't has state.
const UserPassword = React.createClass({
render() {
return <p>The user password is: {this.props.userpassword}</p>
},
})
// OR
class Userpassword extends React.Component {
render() {
return <p>The user password is: {this.props.userpassword}</p>
}
}
With stateless function.
const UserPassword = function(props) {
return <p>The user password is: {this.props.userpassword}</p>
};
With stateless function, arrow function, destructuring and implicit return.
const UserPassword = ({userpassword}) => <p>The user password is: {userpassword}</p>
Stateless function is great for styling as well.
const PrimaryButton = props => {
const styles = { background: 'red', color: 'white' }
return <button {...props} style={styles} />
}
Stateless function with event handlers.
const Button = props => {
const onClick = e => console.log('You clicked me!')
return <button onClick={onClick}>Click me!</button>
};
Stateless function can have defined defaultProps, propTypes.
import PropTypes from 'prop-types'
const UserPassword = props => <p>The user password is: {this.props.userpassword}</p>
UserPassword.propTypes = {
userpassword: PropTypes.string.isRequired,
}
Username.defaultProps = {
username: 'Jonh',
}
Stateless function can have defined contextTypes (when using context, it's simply passed in as the second argument).
import PropTypes from 'prop-types'
const UserPassword = (props, context) => <p>User password is {context.password}</p>
WowComponent.contextTypes = {
password: PropTypes.string.isRequired,
}