DEV Community

Cover image for React - Stateless function
Sandro Jhuliano Cagara
Sandro Jhuliano Cagara

Posted on • Edited on

3 3

React - Stateless function

Stateless functions are a brilliant way to define highly reusable components. They don't hold state; they're just functions.

const MyExample = () => <div>Hello World!</div>
Enter fullscreen mode Exit fullscreen mode

They get passed props and context.

const MyExample = (props, context) => {
    return <div style={{color: context.color}}>Hi {props.name}</div>
}
Enter fullscreen mode Exit fullscreen mode

They can define local variables, where a function block is used.

const MyExample = (props, context) => {
    const style = {
        fontWeight: "bold",
        color: context.color,
    }

    return <div style={style}>{props.name}</div>
}
Enter fullscreen mode Exit fullscreen mode

But you could get the same result by using other functions.

const getStyle = context => ({
    fontWeight: "bold",
    color: context.color,
})

const MyExample = (props, context) => {
    return <div style={getStyle(context)}>{props.name}</div>
}
Enter fullscreen mode Exit fullscreen mode

They can have defined defaultProps, propTypes and contextTypes.

MyExample.propTypes = {
    name: PropTypes.string.isRequired
}

MyExample.defaultProps = {
    name: "Guest"
}

MyExample.contextTypes = {
    color: PropTypes.string
}
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more