Looking for React Moves

In React/JSX, here is a common pattern:

{name && <Header />}

name is a state variable and <Header /> is a component. If name is not null, than the Header is displayed. If name is null (for example, it hasn’t been entered by the user), then nothing is displayed. This works because the && expression only evaluates to true if both elements are true.

{name === "Mike" ? <Header headerName="Mike"/> : <Header headerName="Some silly name"/>

This one uses the ternary operator to control what’s displayed. If the variable, name, has the value of “Mike,” then <Header is displayed with the headerName (a property I made up) of “Mike”, otherwise with the value of “Some silly name”.

<input type="text" onChange={(e) => setName(e.target.value)}/>

Here we have a text input. When you type something in it, that calls the onChange prop, which in this case is set to a callback function that calls the setName function (this is a useState hook) that will give you the value of the input. You can get this because the onChange event will give you the target.value property, which is whatever’s written in the input.

Anyone else have any React tricks? I feel like I only have like four or five of them and I keep trying to use them for everything. I want to add to my arsenal!

When writing React apps I like to consult these resources:

Hope it’ll help you :wink:

Just to clarify. When using && operator with non boolean values and all of its operands are true, it will return non boolean value. That’s why it’s so useful in React.

false && <MyComponent />
// -> false

true && <MyComponent />
// -> <MyComponent />
1 Like

Thanks, those are great!

Yes, I use the && operator to toggle between nothing and a Component. It’s one of my main techniques and I need to learn more.

I’m not an expert myself but it’d be great if you could share some of your code.

Then someone more advanced could potentially look at it at spot some things that might be improved :wink:

My emotion-app and z-project are both in React and if someone wanted to look at the code and give pointers, I would not turn that down! :slight_smile:

emotion app, an app to help you get in touch with your emotions, deploy: https://kind-poincare-cabd5e.netlify.app
z-project, a blog hooked up to firebase with user auth, storing entries, and the ability to add images, deploy: https://z-project-cactus-wren.netlify.app/