Strahinja Ajvaz
Strahinja Ajvaz

Reputation: 2643

object deconstructing throws an error

I'm passing a style object to a component

<Temp styles={{fontWeight: 'bold', fontSize: '1.6'}} ...otherprops />

When I try to deconstruct it, it gives me an error saying Cannot read property 'fontSize' of undefined.

The way I'm deconstructing it is as follows:

{({styles: {fontSize, fontWeight}}) => /* use the values */ }

The part that I don't get is that when I log styles, it displays the correct value, just when i try to deconstruct it it throws the error.

Upvotes: 2

Views: 55

Answers (1)

Anthony
Anthony

Reputation: 6482

The following outputs 16 2 for me; the only issue I can see from the snippet you provided is the left parenthesis as I pointed out in comments:

class App extends React.Component {
  render() {
    return <Temp styles={{ fontSize: 16, fontHeight: 2 }} />;
  }
}

const Temp = ({ styles: { fontSize, fontWeight }}) => {
  console.log(fontSize, fontWeight);
  return <p>Hi</p>;
};

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Upvotes: 3

Related Questions