Passing props via super(props) when extending another component not working
See original GitHub issueI’m not sure if this is a real issue or not but the behavior was unexpected for me. React version: 0.13.3
I have two components, Shape and Circle. Shape is a general concept and Circle is just a special case of Shape. I’m using ES6 class syntax to define the components. I’m trying to override Shape’s defaultProps by passing props from Circle’s constructor using super(props)
. This isn’t working.
See the following code(or JSBin):
import React from 'react';
class Shape extends React.Component {
constructor(props) {
// At this point, props.shapeType === 'Circle', when Circle component
// Is used
super(props);
}
render() {
// At this point this.props.shapeType is still null,
// I expected it to equal 'Circle'
console.log(this.props);
return <div>{this.props.shapeType}</div>;
}
}
Shape.defaultProps = {
shapeType: null
};
class Circle extends Shape {
constructor(props) {
let propsCopy = Object.assign({}, props);
propsCopy.shapeType = 'Circle'
super(propsCopy);
}
}
React.render(
<Circle />,
document.querySelector('body')
);
Issue Analytics
- State:
- Created 8 years ago
- Comments:6 (1 by maintainers)
Top Results From Across the Web
super props inheritance not working - Stack Overflow
It seems that the props in App doesn't inherit the props of the base component. because whenever I log the value of props...
Read more >Props! — and how to pass props to components in React ...
A common question followed by this act: how to pass the data as params (parameters) from one React component to another component? That's...
Read more >Why Do We Write super(props)? - Overreacted
I wrote super(props) more times in my life than I'd like to know: class Checkbox extends React.Component { constructor(props) ...
Read more >How to Pass Props Object from Child Component to Parent ...
In this guide, we'll go through the React props in detail. ... 2class App extends Component { 3 constructor(props) { 4 super(props); ...
Read more >How passing props to component works in React
That's great! But since props are read-only and must not be changed manually throughout the lifespan of a React application, using only props...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Do not use inheritance to build React components. Try:
Our recommendation is to not use inheritance for React components. https://reactjs.org/docs/composition-vs-inheritance.html
There are many pitfalls, and if you disagree with this recommendation, you’re mostly on your own.