Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,152,357 members, 7,815,757 topics. Date: Thursday, 02 May 2024 at 05:48 PM

Best Ways To Write Cleaner React Code - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Best Ways To Write Cleaner React Code (267 Views)

I Need Help With This React Code. / Best Antivirus And Cleaner App For Android In 2020 / How Do I Write Cleaner Codes In Python? (2) (3) (4)

(1) (Reply)

Best Ways To Write Cleaner React Code by 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 remember 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 remember involves passing string props. When you're passing 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)

Servo GUN / Can I Write Codes With My Smartphone And How Flexible Is It? / Software Creator Urgently Needed For Massive Deal!!!

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 9
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.