Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
46
rated 0 times [  47] [ 1]  / answers: 1 / hits: 28677  / 6 Years ago, thu, december 6, 2018, 12:00:00

Currently I have a class component that contains functions that act as components in my JSX.



Example:



class MyComponent extends React.Component {
MySubComponent = (props) => {
if (props.display) {
return <p>This text is displayed</p>
}
}

render() {
return (
<this.MySubComponent display={true} />
)
}
}


Are there any repercussions to calling components this way? Also is there a term for this?


More From » reactjs

 Answers
10

This results in creating new MySubComponent function for each MyComponent instance, which is not very efficient way of doing this.



There may be only two benefits of having MySubComponent as MyComponent method.



One of them is that MySubComponent can be replaced with another implementation in MyComponent subclass without modifying render function. This isn't idiomatic to React because it promotes functional approach instead of OOP.



Another is that MySubComponent can access MyComponent instance and its properties. This results in design problem because two components are tightly coupled.



Neither of these arguments is substantial in React development. Unless there are specific needs that require MySubComponent to be a part of MyComponent, the former shouldn't be defined as instance method of the latter. It could be just:



const MySubComponent = (props) => {
if (props.display) {
return <p>This text is displayed</p>
}
}

class MyComponent extends React.Component {
render() {
return (
<MySubComponent display={true} />
)
}
}

[#52964] Monday, December 3, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
;