JSX
When utilizing the React framework we write code in JSX. JSX is a syntax extension to JavaScript. This means we are able to write HTML and JavaScript somewhat interchangeably. Here's an example:
const editor = 'emacs';
const element = <h1>{editor} is the best!</h1>;
ReactDOM.render(
element,
document.getElementById('root')
);
As you can see we can declare variables and embed them within our html element using curly brackets{}. It's easy to use but a bit challenging when our code begins to grow and becomes more complex.
Logic
Often times we want to add logic statements to control the flow of our program. Say we wanted to set the value of something based on if another variable was undefined. In vanilla JavaScript we would probably end up with something like this:
if(object.id){
value = `${object.id}`;
} else {
value = '';
}
Although we could add an if statement within our curly brackets I prefer using the ternary operator, &&, ||, etc. It makes our code less "blocky" with fewer lines. Here is what our example could potentially look like within React:
value={ object.id ? object.id : '' }
This accomplishes the same thing and reduces our code length and readability. You could write the same code in vanilla JS and that might be the way you already do things. I would just say that when using React it can sometimes be more challenging to code all the if statements within the curly brackets and keep track of everything. So use ternaries and single lines when you can!
Top comments (0)