NewStats: 3,265,304 , 8,186,314 topics. Date: Saturday, 14 June 2025 at 10:47 AM 2u2e6b

6382y

Best Ways To Write Cleaner React Code - Programming - Nairaland 571u44

Best Ways To Write Cleaner React Code (351 Views)

(4)

(1) (Reply)

skptricks: 9:54am On May 27, 2021
In this tutorial we are going to use discuss on react best practices and best way to write clean code. In general, learning how to write cleaner React code will make you a more valuable and overall happier React developer. Lets quickly jump to react code.

Best Ways to Write Cleaner React Code



1. Make use of JSX shorthands

In the example below, we're using the prop showTitle to display the title of our app within a Navbar component.

// src/App.js

export default function App() {
return (
<main>
<Navbar showTitle={true} />
</main>
);
}

function Navbar({ showTitle }) {
return (
<div>
{showTitle && <h1>My Special App</h1>}
</div>
)
}


Do we need to explicitly set show title to the Boolean true? We don't! A quick shorthand to is that any prop provided on a component has a default value of true.



So if we add the prop showTitle on Navbar, our title element will be shown:

// src/App.js

export default function App() {
return (
<main>
<Navbar showTitle />
</main>
);
}

function Navbar({ showTitle }) {
return (
<div>
{showTitle && <h1>My Special App</h1>} // title shown!
</div>
)
}


Another useful shorthand to involves ing string props. When you're ing a prop value that's a string, you don't need to wrap it in curly braces.



If we are setting the title of our Navbar, with the title prop, we can just include its value in double quotes:

// src/App.js

export default function App() {
return (
<main>
<Navbar title="My Special App" />
</main>
);
}

function Navbar({ title }) {
return (
<div>
<h1>{title}</h1>
</div>
)
}


2. Reduce prop drilling with React context

Read More...

(1) (Reply)

Computer Science Ebook!!!

(Go Up)

Sections: How To . 9
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or s on Nairaland.