Alternative to React Fragment

In React you can use fragments:

jsx
import React from 'react';

const App = () => {
    
    return(
        
        <React.Fragment>
            <h1>Title</h1>
            <p>Text</p>
        </React.Fragment>
        
    );
    
}

export default App;

If you check the previous app on the browser, you'll see the following HTML structure rendered:

html
<h1>Title</h1>
<p>Text</p>

As you can see, fragments are useful to prevent creating additional blocks, such as:

html
<div>
    <h1>Title</h1>
    <p>Text</p>
</div>

Alternative

Instead of fragments, you can use the following blocks:

jsx
<>
    <h1>Title</h1>
    <p>Text</p> 
</>

Again, React will render the following HTML structure:

html
<h1>Title</h1>
<p>Text</p>

They are convenient for add text to a component in ternary operators.

Example:

jsx
import React from 'react';

const App = () => {
    
    const [weather, setWeather] = useState(null);
    
    return(
        
        <div className = 'App'>
            { weather === 'sunny' 
            ? <><SunnyButton/> Today is a sunny day</>
            : <><RainyButton/> Today is a rainy day</>
            }
        </div>
        
    );
    
}

export default App;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.