Hi I am learning props validation. I am having two functions APP and Person. From the Person function I am passing variables to the APP. The variables are(Name, preferredCities, Age). I need to apply validations as follows
- Name: Should be a string
- Prefered Cities: Array type
- Age: Should be number and should be greater than 18 and less than 60 for above passed variables.
While executing this app if validation fails I need to pass default values(Name:"Steve", preferredCities:['Chennai','BLR'],Age:18). I wrote the logic for the above problem but when I am trying to render the output based on the condition using ternary operation my logic is not working. Any one can guide me where I am making mistake. Thanks in advance.
const Person = (props) => {
return (
<ul>
<li>
{props.strName === props.strName ? (
props.strName
) : (
<p>{Person.defaultProps.Name}</p>
)}
</li>
<li>{props.num}</li>
<li> {props.arr}</li>
</ul>
);
};
Person.propTypes = {
strName: PropTypes.string,
num: PropTypes.number,
arr: PropTypes.array.isRequired,
};
Person.defaultProps = {
Name: "Steve",
preferredCities: ["Chennai", "Bangalore"],
age: 18,
};
function App() {
return (
<div className="App">
<Person strName={18} num={18} arr={["A", "B"]} />
</div>
);
}
CodePudding user response:
I think you need to change one of the props.strName to propsTypes.strName.
try this {props.strName === propTypes.strName ? (
.. remaining codes
And I think this is a better way to pass props.
function App() {
const strName ="john";
const num = 18;
const arr =["A","B"];
return (
<div className="App">
<Person strName={strName} num={num} arr={arr} />
</div>
);
}
CodePudding user response:
Try this man :
const Person = ({ strName, num, arr }) => {
return (
<ul>
<li>
{ strName && typeof strName === "string" ? (
strName
) : (
<p>{Person.defaultProps.Name}</p>
)}
</li>
<li>{num}</li>
<li> {arr}</li>
</ul>
);
};
CodePudding user response:
try this : const Person = ({ strName, num, arr }) => { return (
{ strName && typeof strName === "string" ? ( strName ) : ({Person.defaultProps.Name}
)} ); };CodePudding user response:
Default props are not for being taken when prop validation fails. Default props are fallback values when the prop is not passed when it is called in its parent component.
The string and the array validation are normal validations for your use case
For the number, you can have some custom validations:
const isCustomNumber = (props, propName, componentName) => {
const regexPattern = /\b(19|[2-5][0-9])\b/;
if (!regex.test(props[propName])) {
return new Error(
`Invalid prop ${propName} passed to ${componentName}. Expected a number between 18 and 60.`
);
}
};
Then you could have your validation like:
Person.propTypes = {
strName: PropTypes.string,
num: PropTypes.isCustomNumber,
arr: PropTypes.array.isRequired,
};
However, this does not take the default values specified if the validation fails. This is just a type checker at compile time.