Skip to content
Advertisement

destructuring props in component getting different result

New to react world, trying to learn destructuring, have been reading about it but stuck here, if i do it like this function MList({action}) { // const data = [action];} i am just getting ‘cameras’. So how to destructure and get same result as with props below this is Mcard.js:

            <Box pt={1}>
              <MList
                action="cameras"
              />
            </Box>

This is inside MList komponent:

i want to destructure this code ( works gives ‘name’ and ‘ident’):

function MList(props) {

 const initialize = () => {
const data = props[props.action];

if (!data || data.length < 1) {
  return;
}
data.map((e) => {
  collapseStates["" + e.name + e.ident] = false;
  return;
});
setCollapseS(collapseS);
  };

 }

Advertisement

Answer

I don’t know React but destructuring the arguments should be something like the following

function MList({action, ...tail}) {

    const initialize = () => {
        const data = tail[action];

        if (!data || data.length < 1) {
            return;
        }
        data.map(({name, ident}) => {
            collapseStates["" + name + ident] = false;
            return;
        });
        setCollapseS(collapseS);
    };

}

Also I would suggest using data.forEach instead of data.map if you don’t need to save the result in another array

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement