Note: I encounter this specific problem using React Native, but I guess this goes for React in general as well.
I have a react component built using React.Component. I don't need to set state, but I do have props. My proposed syntax was as follows:
class Header extends Component {
constructor(props) {
super(props);
}
render() {
return <div>{this.props.title}</div>;
}
}
I understand I can use a function to construct this component, like this:
const Header = (props) => {
return <div>{props.title}</div>;
}
But I prefer the former, because my component will grow, might have state etc, and I just want to keep all my components built in a similar fashion.
Now, my linter complains about having a useless constructor, but how else do I access the props while keeping a class constructor instead of a function constructor?
Note: I encounter this specific problem using React Native, but I guess this goes for React in general as well.
I have a react component built using React.Component. I don't need to set state, but I do have props. My proposed syntax was as follows:
class Header extends Component {
constructor(props) {
super(props);
}
render() {
return <div>{this.props.title}</div>;
}
}
I understand I can use a function to construct this component, like this:
const Header = (props) => {
return <div>{props.title}</div>;
}
But I prefer the former, because my component will grow, might have state etc, and I just want to keep all my components built in a similar fashion.
Now, my linter complains about having a useless constructor, but how else do I access the props while keeping a class constructor instead of a function constructor?
Share Improve this question edited Mar 3, 2019 at 7:24 Cœur 38.7k26 gold badges202 silver badges277 bronze badges asked Oct 19, 2017 at 18:03 SventiesSventies 2,7564 gold badges35 silver badges53 bronze badges 6 | Show 1 more comment2 Answers
Reset to default 16If you want to use this.props in the constructor, you need to pass props to super. Otherwise, it doesn't matter because React sets .props on the instance from the outside immediately after calling the constructor.
So just simply remove constructor() if useless
you can access props without constructor in a class using "this", like this:
class XXXXXX extends React.Component {
render() {
return (
<div>{this.props.value}</div>
)
}
}
this.props
in your components. It is not a must. – bennygenel Commented Oct 19, 2017 at 18:06super(props)
only required if you are creating a constructor for initialising state? – Sventies Commented Oct 19, 2017 at 18:07state
– Prakash Sharma Commented Oct 19, 2017 at 18:07