Tips for setting a default value for the local file in React Native

I am attempting to assign a default value to my Avatar component in React Native Elements as I do not have all the required icon files prepared. However, when I use the OR logic, it does not seem to work as expected. What is the correct approach to achieving this?

          {sites.map((key) => {
            return (
              <Avatar
                size={32}
                containerStyle={{ margin: 0, padding: "0.1em" }}
                rounded
                source={
                  require("../../assets/" + utils.getPathName(key.properties.nameEN, "icon.png")) ||
                  require("../../assets/default/icon.png")
                }
                onPress={() => {
                  displayModal(key);
                }}
              />
            );
          })}

Answer №1

Here's my suggested approach:

var IMG;
try {
    IMG = require("../../assets/" + utils.getPathName(key.properties.nameEN, "icon.png"));
} catch (e) {
    IMG = require("../../assets/default/icon.png");
}

{
  sites.map((key) => {
    return ( 
    <Avatar 
    // other props...
      source = {IMG}
    />);
  })
}

Answer №2

If you anticipate changes in your icons over time, it is recommended to utilize state.

Moreover, for better management of onError events, consider using Image instead of Avatar.

const icon = require("../../assets/" + utils.getPathName(key.properties.nameEN, "icon.png");
const temp_icon = require("../../assets/default/icon.png");

const MyAvatar = ({ source, size }) => {
  const [avatarSource, setAvatarSource] = useState(source || temp_icon);

  const handleImageError = () => {
    setAvatarSource(temp_icon);
  };

  return (
    <Avatar
      size={32}
      containerStyle={{ margin: 0, padding: "0.1em" }}
      rounded
      renderAvatar={() => (
        <Image
            source={avatarSource}
            onError={handleImageError}
        />
      )}
    />
  );
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a dependable API available for capturing window screenshots using either JavaScript or PHP?

Would it be possible to capture a screenshot of window or div elements using JavaScript? I tried using "HTML5's CANVAS" but the quality of the result was not satisfactory. Is there a more reliable API available for this task? ...

"Troubleshooting: Vue ChartJS Line Chart fails to show data

Hey there! I'm currently working on integrating Chart.js with the vue-chartjs wrapper to build a Line Chart using data retrieved from my API. The data is being successfully logged to the console without any errors, but for some reason, the Line Chart ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

Using Express.js to manage CORS Access-Control-Allow-Origin

Seeking guidance on a strategic approach to address my uncertainties regarding an idea I have. My goal is to implement CORS requests, specifically setting Access-Control-Allow-Origin based on the environment type. Here is my current CORS headers configura ...

Executing a Select Change in a React Application using CasperJS

Has anyone else encountered difficulties with this issue? I have a basic React page set up, with a simple component that renders a select element and triggers a callback function when the value changes. Here is the basic structure of the component: const ...

Guide on implementing factory updates to the display

I am attempting to update a reference within my factory in an asynchronous fashion, but I am not seeing the changes reflected in my view. View <div ng-repeat="Message in Current.Messages">{{Message.text}}</div> Controller angular.module(&ap ...

Strategies for increasing a value within an asynchronous function

I'm facing an issue with incrementing the variable loopVal inside a promise. I've tried to increment it without success. Any ideas on how to make this work? const hi = function(delay) { let loopVal = 1; return new Promise((resolve, reject) ...

Using the ngFor directive, parent and child components can establish communication even with empty arrays

I am working on passing data from a parent component to a child component using the ngFor directive. However, I am facing an issue when some arrays have no length, as I need to indicate to the child component that the array is empty. How can I achieve this ...

An element generated using a JavaScript loop is covering another element in the layout

I am facing an issue with positioning images within a div to a span. The problem arises as the images are overlapping each other and I am uncertain about how to properly place each image when it is added. Below is the code snippet: The CSS: <style ty ...

Verify the front-end application and authenticate the backend REST API

My project involves developing a REST API and application logic on the client-side, keeping them separate and independent of each other. Now I am looking to implement an authentication system that will automatically authenticate users both on the client-si ...

Encountering issues with integrating an external plugin with AngularJS code

For my app, I am attempting to incorporate intercom for monitoring user activity. It functions correctly when placed inside a script tag in index.html. However, I encounter an error when trying to use it in a .ts file as shown below: app/components/rocket/ ...

Generate a list of keys along with an array containing sets of values

In my thesaurus app, users can enter a base word like "dog" and its synonyms like "canine, hound, mutt." Once entered, these words are stored in a database. However, to streamline the process and avoid multiple form submissions, I want to create simultaneo ...

Error: Unable to update Ember Array - Property 'destroy' cannot be read because it is undefined

Is there a way to efficiently update an Ember Array so that changes in the array reflect in the view? Take a look at this simplified code snippet - cacheArr: Em.A([]), count: 1, updateFxn: function() { this.incrementProperty(count); devObj = Embe ...

Issue with updating state in child component preventing addition to state

Recently, I made the switch to TypeScript in my NextJS project using Create T3 App. One of the components in my app involves updating the state after a Prisma mutation is performed. I attempted to pass the setItems (which was initialized with useState) to ...

React: When component is suspended, the useEffect hook is not triggered

Exploring the world of react hooks and react suspense has led me to creating a custom hook called useApolloQuery. This hook is designed to fetch data and utilize a promise to wait until the data is loaded. My approach involves placing the data fetching lo ...

Implementing SVG in NextJS 13 with custom app directory: A step-by-step guide

Recently, I decided to explore the app directory and unfortunately ran into some issues. One of the main problems I encountered was with image imports. While PNG images imported without any problem, SVG images seemed to break when importing in /app. For i ...

I'm looking to learn how to efficiently write file chunks from a video upload in Node Js. How can I

My current project involves attempting to stream webcam or audio data to Node.js and save it on disk. The aim is to send the chunks of data to the server as soon as they are available. I have successfully captured the stream using getUserMedia, set up me ...

Where's the tsconfig.json for Firebase Emulators?

I've encountered an issue with my Firebase project that's written in JavaScript (not TypeScript). When attempting to run the functions emulator, I'm getting the following error: $ firebase emulators:start --only functions ⚠ functions: Ca ...

Exploring the depths of nested data retrieval using the fp-ts library: a labyrinth

Embark on your journey into the world of functional programming in typescript using the fp-ts library. I find myself tangled in a complex web of nested data fetching, reminiscent of the ancient Egyptian pyramids. How can I tackle this problem with a more ...

Linking promises together and including extra information to be passed along with the following promises

Can you help me with chaining promises and adding extra data to be returned in the .then, while also making another API request in the process? I've come across similar discussions, but none that show how to include additional data and carry it throug ...