mpen
mpen

Reputation: 282895

React stateless functional components defaultProps function

React 0.14 introduced stateless functional components.

you may still specify .propTypes and .defaultProps by setting them as properties on the function

However, I want to initialize one of the props to a random value (per instance) if it's not set. I can't do that if defaultProps only accepts an object. Is there a way to initialize it using a function, or do I have to create a full React component?

Upvotes: 2

Views: 4712

Answers (2)

Mouad Debbar
Mouad Debbar

Reputation: 3226

If you use the recompose library, you could achieve a solution like this:

import { withState } from "recompose";

var enhance = withState("someProp", "updateSomeProp", (props) => props.someProp || randomValue());
var MyComponent = enhance(function(props) {
  // This is your stateless component.
  return <div>{props.someProp}</div>;
});

This basically creates a wrapper component that contains a state. The state is initialized with a random value if the someProp is undefined.

Upvotes: 1

Cent
Cent

Reputation: 881

The easiest way to get this done is to set the default prop as the random value as Andrew stated.

Component.defaultProps = { 
  someProp: randomValue 
}

If it's set, this default gets overridden, so it works for the behavior you described.

If you want to set the default value using a function, it's basically the same assignment.

Component.defaultProps = { 
  someProp = fxnRandomValue()
}

EDIT:

To make sure all instance truly randomize the value of this prop, I would suggest you skip setting a default prop altogether and do the assignment within the component. Eg.

const statelessComp = ({ prop }) => {
  prop = prop || fxnRandomValue();
  return (
    ...
  )
}

Upvotes: 1

Related Questions