React and the DOM Flashcards
What does the following JSX become when transpiled to JS?
<h1>Hello World</h1>
React.createElement(‘h1’, null, ‘Hello World’)
What are the three main differences between HTML and JSX?
- Tag attributes are camel cased.
- All elements must be balanced.
- The attribute names are based on the DOM API, not on the HTML language specs
Why must all JSX elements be balanced?
Because it’s XML
What does “all JSX elements need to be balanced” mean in practice?
Tags such as <br></br> and <img></img>, which don’t have ending tags,
need to be self-closed. So, instead of <br></br>, use <br></br> and instead of <img></img>, use <img></img>
What does “the attribute names are based on the DOM API” mean in practice?
When interacting with the DOM API, tag attributes may have different names than those you use in HTML. One of such example is class and className. e.g.
<div></div>
if you want to manipulate the DOM and change its class name using plain JavaScript, you’d do:
document.getElementById(“box”).className=”some-other-class”
As far as JavaScript is concerned, that attribute is called className, not class. Since JSX is just a syntax extension to JavaScript, it conforms to the attribute names as defined in the DOM. That same div should be expressed in JSX as:
return <div></div>
Why doesn’t this work?
return (
<h1>Hello World</h1>
<h2>Have a nice day</h2>
)
It’s the equivalent of returning two things in JS which you’re not allowed to do?
How can we solve the below problem:
return (
<h1>Hello World</h1>
<h2>Have a nice day</h2>
)
Return a single DOM node:
return ( <div> <h1>Hello World</h1> <h2>Have a nice day</h2> </div> )
Can we use if statements in JSX?
No, it gets converted into invalid JS
What are the two alternatives to using if statements in JSX?
Use a ternary operator or take the if statement out of the JSX
How does React/JSX handle null and undefined?
It just outputs nothing
How will React render this:
return (
<a>Google</a>
<a>Facebook</a>
)
With no space between the links (unlike HTML where the browser would put a space in)
How can we render a space with React?
{‘ ‘}
How do we create a comment in JSX?
{/* my comment here */}
What is React’s built-in XSS attack protection?
By default it won’t allow HTML tags to be generated dynamically and attached to JSX
Give an example of when you might want to generate HTML on the fly?
Rendering data in markdown format to the interface