JSX
Table of Contents
Reading material
- https://legacy.reactjs.org/docs/introducing-jsx.html
- https://react.dev/learn/writing-markup-with-jsx
JSX Rules
Return single element (one parent element)
-
semantics section/article
-
Fragment - let’s us group elements without adding extra nodes
return <React.Fragment>...rest of the return</React.Fragment>; // shorthand return <>...rest of the return</>;
-
This is not valid.
function Greeting() { return ( <div className='someValue'> <h3>hello people</h3> <ul> <li> <a href='#'>hello world</a> </li> </ul> </div> <h2>hello world</h2> <input type='text' name='' id='' /> ); }
Error
["ERROR" - 11:34:41 PM] Error formatting document. ["ERROR" - 11:34:41 PM] Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>? (30:7)
- This is valid.
function Greeting() { return ( <> <div className="someValue"> <h3>hello people</h3> <ul> <li> <a href="#">hello world</a> </li> </ul> </div> <h2>hello world</h2> <input type="text" name="" id="" /> </> ); }
which is the same as
function Greeting() { return ( <React.Fragment> <div className="someValue"> <h3>hello people</h3> <ul> <li> <a href="#">hello world</a> </li> </ul> </div> <h2>hello world</h2> <input type="text" name="" id="" /> </React.Fragment> ); }
camelCase property naming convention
// in JSX
return (
<div tabIndex={1}>
<button onClick={myFunction}>click me</button>
<label htmlFor='name'>Name</label>
<input readOnly={true} id='name' />
</div>
)
// in html
<div tabindex="1">
<button onclick="myFunction()">click me</button>
<label for='name'>Name</label>
<input readonly id='name' />
</div>
className instead of class
return <div className='someValue'>hello</div>;
close every element
return <img />;
// or
return <input />;
formatting
opening tag in the same line as return or ()
const Greeting = () => {
return <h2>My First Component</h2>;
};
or
function Greeting() {
return (
<>
<div className='someValue'>
<h3>hello people</h3>
<ul>
<li>
<a href='#'>hello world</a>
</li>
</ul>
</div>
<h2>hello world</h2>
<input type='text' name='' id='' />
</>
);
}