Funny things that can happen in React.js

Robert Chen
4 min readJan 28, 2019

--

I’ve been learning React.js for the past three weeks and I wanted to share some of the funny/interesting moments and pieces of code that I had to write or helped write to make things work. There are definitely better ways to achieve what we needed to do, but these were some pretty fun solutions that we came up with and wanted to share.

We’ll start off light with some css manipulation, here’s some simple css:

.gryffindor {background-color: #7f0909;color: #ffc500;}.slytherin {background-color: #0d6217;color: #aaaaaa;}.hufflepuff {background-color: #eee117;color: #000000;}.ravenclaw {background-color: #000a90;color: #946b2d;}
  1. Dynamically changing a form’s styling with className and nested ternaries
<formclassName={this.state.house === "Gryffindor"? "gryffindor": this.state.house === "Slytherin"? "slytherin": this.state.house === "HufflePuff"? "hufflepuff": "ravenclaw"}onSubmit={this.submitHandler}>

I discovered this on my first weekend with React. At the time, I didn’t know all that much about React but I knew JSX takes javascript since I’ve seen this:

value={ condition ? do this : else do this }

I thought if that works with the value tag, then it should also work with className and while I’m at it, why not try it with nested ternaries? To my pleasant surprise, that worked exactly the way I wanted it to. Rare happening sighted! That was cool and it made the app a little more fun to engage with.

Disclaimer: The following two code snippets are from Raquel and Manny’s Mod 4 Project. Through a culmination of their hard effort, the app resulted in an incredible piece of work. I only checked in briefly to help with the following two brain teasers.

2. Map Map Find Filter

{this.props.playlist.map(pl =>
(<div><h3>{pl.name}</h3>
{this.props.playlistTracks.map(plt => (plt.playlist_id === pl.id ?<PlaylistTrack playlist={this.props.playlist.find(pl =>
plt.playlist_id === pl.id
)}
tracks={this.props.tracks.filter(track=> (
track.id === plt.track_id
))}
/>
: null))}

This one was tough, an iteration nightmare that we set ourselves up for. We have three arrays of objects at play here. For starters, we have a playlist array that we have to map through to display the playlist’s name as a title, then map through playlistTracks to find the desired playlist so that we could render the correct tracks via a filter. This was a debugging hell, knowing what iteration we’re currently in and how each prop needs to interact with the other props considering we had playlist, playlistTrack, and track all mapping, finding, and filtering back to back. I figured this one out with Raquel while working through lunch. We were so glad we got through that and we happily rejoiced until we ran into the next problem.

3. Merging a response with an object that was passed in from a child’s child’s child to setState with the fusioned object.

submitPlaylistHandler= (e, playlistId, track, spotifyId) => {  e.preventDefault()  fetch(`http://localhost:3001/api/v1/playlist_tracks`, {    method: "POST",    headers: {      "Content-Type": "application/json",      Accept: "application/json",      Authorization: localStorage.getItem("token")    },    body: JSON.stringify({      playlist_id: playlistId,      track_id: track.id,      spotify_id: spotifyId    })  }).then(res=>res.json())    .then(data=>{      let fullPlaylist = [...this.state.playlistTracks, data]      let newTrack = {         id: data.track_id,        name: track.name,        artists: track.artists,        image: track.image,        duration: track.duration,        popularity: track.popularity,        preview: track.preview,        spotify_id: track.spotify_id      }      this.setState({        playlistTracks: fullPlaylist,        tracks: [...this.state.tracks, newTrack]      })    }).then(alert(`${track.name} added!`))}

This was madness, I worked with Raquel and Manny on this one for at least two hours. We needed to create a new playlist track, setState with that and also add a new track to the existing tracks array during the setState. Creating the playlist track wasn’t an issue, but adding the track to our tracks array was a problem. We debugged and console logged and debugged some more to finally find out that the track object, only at the moment when passed into our submitPlaylistHandler was returning null as an id. This was an issue because we couldn’t setState without that id. We deduced that it has something to do with the asynchronicity of fetch and setState and everything else that was happening in between.

Then it occurred to me that our playlist_track response had a track_id attribute which should be the same as our missing puzzle piece. Soooo we came up with a clever idea of creating a new object with the combination of playlist_track’s track_id attribute and the rest of the track object’s attributes. Save that into a variable and setState with that fusioned object. Honestly, we didn’t think that would work, but it did and it was AWESOME seeing it happen.

I know these snippets of code are dirty and super hard to read, definitely not recommended for production code. Yet it was darn fun working through those problems and I’m so happy that I found my way into the programming world because of moments like these.

If you enjoyed that, check out my latest series: Learn to code in multiplayer game.

I also do tutoring on the first Monday every month on Meetup.

Find me on Youtube and Twitch for more developer content!

--

--

No responses yet