I have this simplified avatar component:
<template> <img :src="src"> </template> <script> export default { name: 'Avatar', props: { src: { type: String, default: '/static/avatar-default.png' } } } </script>
Let's say I fetch some user data from my API and it contains no avatar URL. In such case I want this component to use the default value but it only seems to work when passing undefined
to it, but undefined
is not valid in JSON so I cannot return that from the API response.
Is there a way to realize what I want by passing in null
or is there a better way to handle this?
If prop values are not passed a certain component, an error will not be thrown. Instead, within the component that prop will have a value of undefined . If you would like to be alerted to when a value is not passed as a prop to a component, you can use a tool like prop-types or TypeScript using these tools.
Default props can be used to define any props that you want to be set for a component, whether or not a value is actually passed in from the parent component. When using default props, you can still override the values specified in the default props object when you pass in values from the parent component.
5. Are default props available in React Native and if yes for what are they used and how are they used ? Yes, default props available in React Native as they are for React, If for an instance we do not pass props value, the component will use the default props value. import React, {Component} from 'react';
You can define default values for your props by assigning to the special defaultProps property: class Greeting extends React. Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); } } // Specifies the default values for props: Greeting.
I would make a computed property based on the src
prop value that will return a default value if the src
is null
:
<template> <img :src="source"> </template> <script> export default { name: 'Avatar', props: { src: { type: String } }, computed: { source() { return this.src || '/static/avatar-default.png'; } } } </script>
You could also explicitly pass undefined
as prop if src
is null
and you'd rather want the component to handle default values.
<template> <img :src="src || undefined"> </template>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With