₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,331,032 members, 8,448,283 topics. Date: Monday, 20 July 2026 at 06:58 AM

Toggle theme

Best Ways To Write Cleaner React Code - Programming - Nairaland

Nairaland ForumScience/TechnologyProgrammingBest Ways To Write Cleaner React Code (402 Views)

1 Reply

Best Ways To Write Cleaner React Code by skptricks(op): 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

I Asked Chatgpt To Write A Poem About Nairaland. Here's The OutputI Need Help With This React Code.Best Antivirus And Cleaner App For Android In 2020234

Low Competition Keywords List 2021Help A Confused Soul: Data Science, BI Analysis Or Software DevelopmentCodeigniter 2 To Codeigniter 3