PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 28, 2022

[FIXED] How can I conditionally include images in React Native Component?

 July 28, 2022     image, react-native, reactjs     No comments   

Issue

I am able to add static images to a ListView cell just fine (see code below), but how do I change the icon image dynamically?

From React Native Docs

<Image source={require('./img/check.png')} />

is the recommended way to reference image files for both iOS and Android.

I have a component called ExpandingCell that has the option to show a bunch of different icons but everything else remains the same.

In a ListView I create a cell object and then pass it into the ExpandingCell to render

the ListView data source array looks like this:

var LIST_DATA = [
 ...
  {type: 'ExpandingCell', 
   icon: './CellIcons/MagnifyingGlassIcon.png', //unused
   title: 'Lorem Ipsum', 
   detail: 'Donec id elit non mi porta gravida at eget metus.'},
...
];

then in renderCell method it gets passed the above cell object:

renderCell(cell) {
    if (cell.type === 'ExpandingCell') {
        return (
          <ExpandingCell cell={cell} />
        );
    }
}

Now in ExpandingCell I have this for render():

render() {
    return (
        ...
        <Image source{
            require('./CellIcons/MagnifyingGlassIcon.png')
        }>
        </Image>
        ...
    );
}

However, when I try to make use of this.props.cell.icon like this:

<Image source={require(this.props.cell.icon)}></Image>

I get the following error: Requiring unknown module "./CellIcons/MagnifyingGlassIcon.png".

Thanks in advance =)


Solution

The images have to be known during packaging. There's a section about it in the docs.

Put this at the top of the file you define ExpandingCell in:

const MAGNIFYING_GLASS_ICON = require('./CellIcons/MagnifyingGlassIcon.png');

Then you can use the constant like this

let icon = someCondition ? MAGNIFYING_GLASS_ICON : SOME_OTHER_ICON;
<Image source={icon}/>

You have to have the requires for all images you want to use this way in there.



Answered By - Daniel Basedow
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing