Nikobitan
Nikobitan

Reputation: 5

CheckBoxes React Native Map function returns error: Too many re-renders. React limits the number of renders to prevent an infinite loop

I have this code, that should draw checkbox'es.

here is my Hashtags.js file:

import React, { useState } from 'react';
import {StyleSheet, View, Image} from 'react-native';
import { CheckBox } from 'react-native-elements';
const HashtagsList =[
  {checked: false, title: '#tip1'},
  {checked: false, title: '#tip2'},
  {checked: false, title: '#tip3'},
  {checked: false, title: '#tip4'},
  {checked: false, title: '#tip5'},
  {checked: false, title: '#tip6'}, 
];

const Hashtags = props => { 
  const [hashtags, setHastags] = useState([]);
  setHastags(HashtagsList);

const toggleCheckbox = (title) =>{   
  const checkedHashtags = hashtags.find((hashtag) => hashtag.title === title);
  checkedHashtags.checked = !checkedHashtags.checked;
  const checkboxes = Object.assign({}, hashtags, checkedHashtags);
  setHastags({ checkboxes });
};

hashtags.map((hashtag, i) => {
  console.log(hashtag);
  return (
    <CheckBox
      key = {i}
      title = {hashtag.title}
      checkedIcon={<Image style={styles.chekBoxPic} source={require('../assets/svg/checked.svg')} />}
      uncheckedIcon={<Image style={styles.chekBoxPic} source={require('../assets/svg/unchecked.svg')} />}        
      checked={hashtag.checked}
      onPress={() => toggleCheckbox(hashtag.title)}
    /> 
    );
 })

};
const styles = StyleSheet.create({   
  chekBoxPic:{
    width: 22, 
    height: 22, 
  },
});
export default Hashtags;

My main.js page looks like this:

...
<View type={styles.someStyle}>
   <Hashtags />
  </View>
...

But i get error:'Too many re-renders. React limits the number of renders to prevent an infinite loop.' Where I make a mistake?

Upvotes: 0

Views: 304

Answers (2)

sushantdsuwal
sushantdsuwal

Reputation: 131

I thinks its probably because of setHastags(HashtagsList) which cause Hashtags component to end up in an infinite loop.

you can initialize the initial HashtagsList like:

const [hashtags, setHastags] = useState(HashtagsList);

Upvotes: 2

Niekert
Niekert

Reputation: 947

I think the problem is in the first few lines of your HashTags component:

const Hashtags = props => { 
  const [hashtags, setHastags] = useState([]);

  // Every time your react component re-renders, it sets the state
  // Of the hashtags. This causes the component to end up in an infinite loop
  setHastags(HashtagsList);
}

Instead of setting the initial hashtags separately, you can initialize it in the useState call, like this:

const Hashtags = props => { 
  const [hashtags, setHastags] = useState(HashtagsList);
}

Upvotes: 0

Related Questions