Home > front end >  How do I manipulate state from a child component using props and spread operator?
How do I manipulate state from a child component using props and spread operator?

Time:11-25

I am passing down props.key and props.expansion, whose data types are string and an object respectively.

In the if statement, the JS engine throws an error for the second argument that is after the spread operators(props.key: true), with the error message saying a comma is required. I do not see any error in the code.

Please point out and suggest a solution for the arguments(particularly the second argument) of props.selectExpansion in the if statements.

const Expansion = (props) => {

return (
    // unique props.key is the expansion name
    <div className={props.key} onClick={() => {
    // only alters the expansionList state by changing the expansion name corresponding to props.key
        
    // change the boolean value of expansion on expansionList
        if(!props.expansion[props.key]) {
            props.selectExpansion(...props.expansion, props.key: true)
        } else {
            props.selectExpansion(...props.expansion, props.key: false)
        }
    }}>
        
      <h1>Expansion</h1>
    </div>
    );
}
 
export default Expansion;

CodePudding user response:

It's hard to say what is the props.expansion anyway if you want to change something inside of that object, code could be changed to the following:

// change the boolean value of expansion on expansionList
if(!props.expansion[props.key]) {
    props.selectExpansion({...props.expansion, [props.key]: true})
} else {
    props.selectExpansion({...props.expansion, [props.key]: false})
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

For better understanding, I think we need to see the parent component but I think you are trying to set the state as it is just with the updated key value. Hence you need to wrap the params in an object.

const Expansion = (props) => {

return (
    // unique props.key is the expansion name
    <div className={props.key} onClick={() => {
    // only alters the expansionList state by changing the expansion name corresponding to props.key
        
    // change the boolean value of expansion on expansionList
        if(!props.expansion[props.key]) {
            props.selectExpansion({...props.expansion, props.key: true})
        } else {
            props.selectExpansion({...props.expansion, props.key: false})
        }
    }}>
        
      <h1>Expansion</h1>
    </div>
    );
}
 
export default Expansion;
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

See I have used this

props.selectExpansion({...props.expansion, props.key: true})

Instead of

props.selectExpansion(...props.expansion, props.key: true)

Earlier you were passing 2 params to the setState(selectExpansion) function.

  • Related