Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use default value if prop argument is null

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?

like image 856
Kid Diamond Avatar asked Jan 10 '18 20:01

Kid Diamond


People also ask

What is the default value for a prop if no value is passed to it?

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.

How to set default props React?

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.

Are default props available in React native and if yes for what are they used and how are they used?

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';

How to set default props in functional component 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.


2 Answers

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> 
like image 68
thanksd Avatar answered Sep 24 '22 03:09

thanksd


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> 
like image 29
nomadoda Avatar answered Sep 25 '22 03:09

nomadoda