Welcome, Guest: Join Nairaland / LOGIN! / Trending / Recent / New
Stats: 2,777,010 members, 6,616,424 topics. Date: Saturday, 04 December 2021 at 02:21 PM

Best Ways To Write Cleaner React Code - Programming - Nairaland

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

Best Ways To Increase Sales On Ebay / 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
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)

My Portfolio Site / Frontend Web Developer. In Search Of Full Time Job. / How Do You Learn? Learning Insights For A Live-low Cost Tech Courses Marketplace

(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 - 2021 Oluwaseun Osewa. All rights reserved. See How To Advertise. 38
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.