In this lesson, it mentions that the process for rendering JSX elements and React components is slightly different in regards to the syntax for the thing you want to render. I understand the difference in syntax, however, this has made me realize that I do not understand the difference between a JSX element and a React component. As far as I can tell, a React component is basically a JSX element that is created by being returned by a nameless function, or by being returned by rendering through a class. Am I missing something here? Are they functionally different?
2 Likes
React Component is that function or class returning JSX Element
Okay, so JSX elements are only accessibly through React components?
A React element using JSX syntax (looks just like html but it’s more than that):
const element = <h1>Hello, world</h1>;
Functional Component:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
Class Component:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
1 Like
So I’m basically only going to use JSX elements within React components, and not on their own?
Well, first of all, they are all JSX elements:
<Header /> // <-- Check if DOM Element, if yes create it, if no invoke new Header (or something like this)
<h1>Hello World!</h1> //<-- Check if DOM Element, if yes create it, if no invoke new Header (or something like this)
You can use JSX outside React Component in any environment using @babel/preset-react
:
const component = <h1>Types of Food:</h1>;
class TypesOfFood extends React.Component {
constructor(props) {
super(props);
}
render() {
return component
}
};
ReactDOM.render(<TypesOfFood />, document.body)
Or you can store it as a string in any environment and then inject it in the component:
const component = '<h1>Types of Food:</h1>'; // String
const TypesOfFood = () => <div dangerouslySetInnerHTML={{__html: component}} />;
ReactDOM.render(<TypesOfFood />, document.body);
Though, name dangerouslySetInnerHTML
suggests you shouldn’t probably do that