10

I have an empty object initially.

const foo = {}; 

It will be going to change to,

const foo = { a: 'data', b: 'data', . . nth }; 

How to define PropTypes for this or do I need to make custom type checker for this ?

3
  • Your problem being that it changes from an empty object to a specific shape? Commented May 22, 2018 at 6:47
  • yes thats the condition Commented May 22, 2018 at 7:22
  • 1
    I have found solution from this post. Commented May 22, 2018 at 10:37

3 Answers 3

12

You can use like this:

All values of object should have instance of String:

foo: PropTypes.objectOf(PropTypes.string), 

For further interest:

Any values of object can be passed:

foo: PropTypes.objectOf(PropTypes.any), 

Object can only have a and b as its property:

foo: PropTypes.shape({ a: PropTypes.string, b: PropTypes.number }), 

Or, custom validation:

foo: function(props, propName, componentName) { if (!/matchme/.test(props[propName])) { return new Error( 'Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.' ); } }, 
Sign up to request clarification or add additional context in comments.

Comments

1

To define your shape with PropTypes you would use something like:

import PropTypes from 'prop-types'; // your component const Component = () => <p>Hello world</p> Component.propTypes = { foo: PropTypes.shape({ a: PropTypes.string, b: PropTypes.string, }), } 

Apart from that I'm not sure what you mean :)

1 Comment

sorry, i forgot to write n'th data, there is n'th data inside object, which means dynamic data.
0

It really depends on whether you would like your object to be strongly typed or not. JS can be incredibly free with object types or you can use something like typescript to make everything strongly typed.

Im not entirely sure what you mean by a custom type checker, but if say this is being populated by a something external and you always want the variables in the object to be of type int, then you could add some logic to do so.

If you are more precise with the whole problem maybe I can help you futher

1 Comment

I think the question is specifically about prop-types

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.