0

I want to use .map like this. I define array like new array(4) and I dont give anyitem. So when I use like this :

      imgUrls.map((url, index) => {
..
});

*this doesn't run 4 times. why ? I have default img so if imgUrls' first item is empty then use defaultimage. if second is empty then use defaultimage ... it should go like this but i couldnt solve *

My code which I try is below

 constructor(props) {
        super(props);

        this.state = {
          imgUrls: new Array(4),  
          defaultImage: require('../Images/addcircle.png'),   
        };
      }

renderContent = () => {
        const { imgUrls } = this.state;

            return imgUrls.map((url, index) => {

                try {
                    return (
                        <View key={index} >

                          <TouchableOpacity onPress={() => this.removeImg(index)}>
                            <View style={{ height: '100%', justifyContent: 'center', alignItems: 'center', aspectRatio: 1 }}>                  
                                            <Image
                                            source={{ uri: url } || this.state.defaultImage}
                                            style={{ height: '90%', width: '90%' }}
                                            /> 
                            </View>
                          </TouchableOpacity>

                        </View>
                        );
                } catch (error) {
                    console.log('error:', error);
                }
            }); 

      };


 render() {
        console.log('in bar');             
        return (

            <View style={styles.container}>
             {this.renderContent()} 
            </View>
)
}
2
  • Within the map you shouldnt need the trycatch. Also assign your new array to a variable and return the variable in render content. Commented Apr 4, 2019 at 11:20
  • little example ? I tried what u said but didnt work. imgUrls.map shouldn run 4 times ? Commented Apr 4, 2019 at 11:23

1 Answer 1

1

This one creates an empty arry that you can map over :)

const arr = Array.apply(null, Array(5));
arr.map(() => {}) // <- this one will work

This one creates an empty arry that you cann't map over

const arr = new Array(5);
arr.map(() => {}) // <- this one will not work
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.