and what is the need of rendering components like this
I’m not able to get big picture why are we doing it like this , what’s the need
a few examples would help.
const ChildComponent = () => {
return (
<div>
<p>I am the child</p>
</div>
);
};
class ParentComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>I am the parent</h1>
{ /* change code below this line */ }
<ChildComponent />
{ /* change code above this line */ }
</div>
);
}
};
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.123 Safari/537.36.
The only reason to break such structure in sub-components - readability, you want to keep your components lean and preferably doing one thing only in the DOM
Dynamic - components that might be composed in variety of ways:
const Parent = ({ children }) => (
<div>
<h1>My heading</h1>
{ children }
</div>
);
The idea behind components is to reuse user interface elements, instead of writing them over and over again / to rendering them dynamically. They are nested because simpler components can make up various complexer components. e.g. like a button can be useful in various places, not only in one specific form;
Yes. Not in the granular html-element sense, but parts of code that belong to together, often with some styling. e.g. cards, lists, menus … here is a list that gives an overview of common components: https://material.io/components
I am not sure I fully understand that question. I think the answer is no, if you mean “render only other components and have no content of its own”. e.g. the part below (from this exercise) renders two nested components plus some markup of its own - the div and h1 …
class TypesOfFood extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>Types of Food:</h1>
{/* change code below this line */}
<Fruits />
<Vegetables />
{/* change code above this line */}
</div>
);
}
};
// change code below this line
ReactDOM.render(<TypesOfFood />, document.getElementById('challenge-node'));
In react there are famously two types of components (I’m pretty sure it’s well covered in the curriculum) - functional and class components. A bit more than a year ago react team admitted that it was a mistake to split components in those categories and suggested everyone to use functional components only. It’s fair to say that class components become obsolete at this point.
React components are just functions and as any function they can return anything they like. This is valid react component believe it or not:
const FortyTwo = () => 42;
You preferably want components to be a bit more useful and therefore most of the time you would return JSX template.
When you declare function that returns JSX, it is expected for React to be in scope. You don’t need to extend anything, like you do with classes or actually use React when you’re declaring functional components.