crud in Rails and React | Tutorial
In this tutorial we are going to clone down a repo with a Rails API and build out a React front end using the react-rails gem. We won't cover the Rails API in detail and it is assumed that you are familiar with the general structure of a Rails project and JavaScript syntax.
In your terminal, clone the project:
$ git clone [email protected]:applegrain/creact-starter.git; cd creact-starter $ bundle install $ rake db:setup
If you were instead to run
$ rake db:{create,migrate,seed}you might have trouble and get something like
NoMethodError for details=. This is because when we manually run the
migratecommand, Rails doesn't know that it needs to reset column information on what was just migrated to account for potentially new columns, so it hiccups trying to call methods on those columns. Conversely, the
setupcommand includes a step for resetting columns, so we're in the clear to then call methods.
run tests with:
$ bundle exec rspec
and start the server with:
$ bundle exec rails s
If you start the server and go to
http://localhost:3000you'll see an
h1tag and many skills - each with a name, details and a level set as enum. The seed data doesn't really reflect the fact that it is a skill. Feel free to change the Faker options in
db/seeds.rb.
In
config/routes.rbthere is already a root path set up. This will be the only route we are going to use. We also have a
app/controllers/site_controller.rbwith an index action that passes the instance variable
@skillsto the view. In the view,
app/views/site/index.html.erb, we are iterating over
@skillsto render all the skills on the DOM. Later we are going to delete the instance variable in the action and have an almost empty view.
In
config/routes.rbthere is also routes for
Api::V1::Skills. The json API is already built out with the necessary actions. In
app/controllers/api/v1/skills_controller.rbwe are serving json from four endpoints.
Further resources on building a json API
React.js is a "JavaScript library for building user interfaces". It's a tiny framework used to build your view layer. React can be used in combination with almost any back end, and can be combined with other front end frameworks as well. React, can be sprinkled in anywhere in your Rails application. React could be used for a search bar, be part of the nav bar or be used for the whole page.
React is a JavaScript library but fortunately we can use the react-rails gem that enables us to use React and JSX in our Rails application. You'll get more familiar with JSX a bit further down but it's basically the equivalent to erb. It's how we mix JavaScript with HTML - the same way we can mix Ruby with HTML when we use erb.
Add
gem 'react-rails'to your Gemfile.
$ bundle $ rails g react:install
The last command generated a file, created a directory and inserted three lines to our code.
$ rails g react:install create app/assets/javascripts/components create app/assets/javascripts/components/.gitkeep insert app/assets/javascripts/application.js insert app/assets/javascripts/application.js insert app/assets/javascripts/application.js create app/assets/javascripts/components.js
If you open up
app/assets/javascripts/application.jsyou'll see the three lines React inserted.
//= require react //= require react_ujs //= require components
Just like jQuery, we require
react,
react_ujsand
componentsto the asset pipeline. In
app/assets/javascripts/components.jswe require the directory
components. It's in this directory where all our React components will live. Think of a component as a type of class, it represents a "unit" of code. We build many small components that we combine to build bigger features.
The notation for rendering React components is: .
Components have parent-child relationships, if component "Cat" renders component "Kitten", "Cat" is the parent of "Kitten". As an example, let's build the component hierarchy for a site with a header, a side bar and tweets:
The main component,
, will render the
and component. The
Headerand the
Bodycomponents exist independently of each other but they need to know about similar data, such as the current user or which link in the header was clicked last. We can store that information and keep track of the current state of our application in
Mainand pass it down to
Headerand
Body. By storing the data in one place we are also only updating the data in one place - we have a so-called "Single Source of Truth", one place where data is stored and updated.
In
, we render and . and don't really depend on the same data but rendering both of them in theBodymakes sense since they might share styling attributes. Finally, renders an entire collection of . Each individual tweet is a single
Tweetcomponent to keep it DRY: "Don't Repeat Yourself".
Main / \ / \ Header Body / \ Ads Tweets \______ | Tweet | _\_ | / \ | Body TweetOptionsBars | |___ | Tweet | _\_ | / \ | Body TweetOptionsBars | etc
additional resources on component hierarchy: - Thinking in React - Video tutorial that walks through the code used in above article
Now we need to connect our Rails views to our (yet non-existent) React code. First, add a file to the components directory. This will be our main file.
$ touch app/assets/javascripts/components/_main.js.jsx
The
.js.jsxextension is similar to
html.erb. In Rails views, we write erb that gets compiled down to HTML. With
js.jsxfiles, we write JSX that gets compiled to JavaScript.
Then we establish a connection between the Rails view and the main component. To render
_main.js.jsxin our root we need to add the view helper we get from the react-rails gem. It puts a div on the page with the requested component class. Go ahead and delete the old code in the view. Since we use React as our view layer, our Rails views are next to empty (as they should be).
Since the Rails asset pipeline will take all of our JavaScript and mash it together, the names of the JavaScript files don't really matter. Below, React will look for a component that's named
Main.
app/views/site/index.html.erb ```
<%= react_component 'Main' %>
And let's add our first React component - head to the browser and make sure it works.
app/assets/javascripts/components/_main.js.jsx
var Main = React.createClass({ render() { return (
If you're receving an error about Rails not recognizing your react_components, be sure to restart your server.
5. Hello, Creact!
We did it! We have copy-pasted our first component and our Rails view is empty. Let's take a closer look at
Main
.We have built a component and given it a name. It has only one function,
render()
. When a React component is mounted on the DOM, itsrender()
method will execute and also trigger it's children'srender()
methods. The code that's in thereturn
statement is the JSX that will render on the page. Right now our HTML looks like regular HTML, but soon we will add in some JavaScript so it becomes more dynamic. Each React component can only return one element, so all JSX elements in the return statement need to be in one wrapper div.
Bad - returning sibling HTML elements that aren't wrapped by a shared parent div.
return (
All of the contents
Better - we have multiple sibling HTML elements which share a parent div.
return (
All of the contents
Let's build out the component hierarchy. We are going to implement basic CRUD functionality; create, read, update, delete. Our
Maincomponent could render a
Headerand a
Body. In the
Body, we need to be able to view all skills, create a new skill, edit a skill and delete a skill. So,
Bodycould render and .
NewSkillis a form to create new skills and
AllSkillsrenders a collection of individual
Skillcomponents - each
Skillcomponent has it's own delete and edit button.
Main / \ Header Body / \ NewSkill AllSkills \ Skills * n
Let's remove our current
h1and add
in it's place.
app/assets/javascripts/components/_main.js.jsx
var Main = React.createClass({ render() { return () } });
We are rendering the
Headercomponent (still non-existent) in the
Maincomponent, which makes
Headerthe child of
Main.
$ touch app/assets/javascripts/components/_header.js.jsx
Our code for the
Headercomponent will look very similar to what we have in
Main. For now, put an
h1in the return statement with whatever text you want. Hop over to your browser to make sure the
h1renders as it should. If not, take a look at the code we first had in
Mainand compare the syntax. Let's leave the
Headerfor now and move on to building out the body.
Now let's render all skills on the page. First, we need to add a
Bodycomponent in which our
NewSkilland
AllSkillscomponents will be rendered.
$ touch app/assets/javascripts/components/_body.js.jsx $ touch app/assets/javascripts/components/_all_skills.js.jsx $ touch app/assets/javascripts/components/_new_skill.js.jsx
Go ahead and add the code from
Headerin the
Body,
AllSkillsand
NewSkillcomponents.
Bodyshould render
AllSkills. Put an arbitrary
h1in
AllSkillsso we can get some feedback on the page. At this point, two
h1's should be rendered on the page. If they don't, open up the dev tools (option + cmd + i) and see if you have any errors in the console. If they aren't useful, look over the syntax carefully and make sure it looks like what we have in
Main.
Our next step is to fetch all skills from the server. We will use Ajax to ping the index action of our Rails API to get all the skills from the database. It's important that our Ajax call is only executed once. It's expensive to make Ajax calls and depending on the scale of your applications, it can cause performance issues. If we were using jQuery, we would implement this in a
$(document).ready()function.
React components have some built in methods available that execute during different points during a component's lifecycle. Some examples include functions that execute before/after a component mounts on the DOM and before/after it dismounts. In this case, we want a method that renders once when the component is mounted on the DOM. We are going to use
componentDidMount()which is called right after the component is mounted. For more details about methods that are available to components and when to use them, check out the docs.
Let's add a
componentDidMount()function and just
console.log()something so we now it's being called.
app/assets/javascripts/components/allskills.js.jsx ``` var AllSkills = React.createClass({ componentDidMount() { console.log('Hello'); },
render() { return (
Why is there a comma at the end of our function? Take a closer look at the syntax. When we write
var AllSkills = React.createClass( /* Code here */ )
we give it an object containing all the code for the component. Since elements in objects are comma separated, we put a comma at the end of our functions.Did you see the output from the
console.log()
in the browser console? Cool! Let's see if we can fetch all skills.
$.getJSON('/api/v1/skills.json', (response) => { console.table(response) }); ```
Make sure to look in the browser console to make sure everything looks good.
Right now we are just logging the result to make sure we get the objects we want. Really, what we want to do is to store it on the component so we can use it more easily throughout our application. Data that will change is stored as
stateon the component. In React, state is mutable, so data that will change throughout the program should be stored as state.
getInitialStateis another method we get from React and it's used to specify the initial values for all the states in the component. Let's create a state called
skillsand set it equal to an empty array.
app/assets/javascripts/components/allskills.js.jsx ``` var AllSkills = React.createClass({ getInitialState() { return { skills: [] } },
// rest of the component
Now, when we get the response back from the server, we want to update
skills
and set it to the value of the skills we got from the server. We want to store it as state because when we add new skills, we want to be able to render them on the page without having to ping the index action of our API again. By using another of React's built in methods, this isn't bad at all.
$.getJSON('/api/v1/skills.json', (response) => { this.setState({ skills: response }) }); ```
To be sure that we actually updated the state, let's log the state (
console.log(this.state)) in the
render()method. Make sure to put it outside of the return statement! You should see something like the following in your browser console.
this.state.skillsis how we would access the skills array.
> Object {skills: Array[0]} > Object {skills: Array[50]}
We might eventually want to create a
Skillcomponent for each object in the skills array. For now, let's just map over the objects in the array and create DOM nodes out of them. Since JSX is just HTML + JS, we can build HTML elements and insert JavaScript wherever we need it, similar to how we can insert Ruby in HTML elements using erb.
app/assets/javascripts/components/allskills.js.jsx ``` // componentDidMount() and getInitialState()
render() { var skills = this.state.skills.map((skill) => { return (
Level: {skill.level}
{skill.details}
return({skills})
} ```
The return value from the
this.state.skills.map...will be an array of HTML divs, each with an
h3and two
ptags (if you don't believe me, log the return value and look). As you can see, inserted JavaScript needs to be enclosed in curly braces - the erb equivalent to this would be . In the return statement we have replaced the
h1tag with the skills array we built above. In the return statement we write JSX and our skills array is JavaScript, so in order for it to be evaluated it needs to be wrapped in curly braces. Head over to the browser and make sure it all works ok!
You should see an error like this in the browser console:
Each child in an array or iterator should have a unique "key" prop. Check the render method of `AllSkills`. See https://fb.me/react-warning-keys for more information.
A key prop?
When we are rendering multiple similar HTML elements - in our case, 50 of the same type - we need to supply each with a unique key. React uses a diffing algorithm to figure out which parts of your application has changed and needs to be re-rendered. This is partially what makes React so fast and snappy in the browser. It uses the keys to identify the DOM nodes and if we have several on the same kind, the diffing algorithm doesn't work as it should. For more details on this topic, check out the docs.
Let's help React out and add a key prop.
var skills = this.state.skills.map((skill) => { return () });{skill.name}
Level: {skill.level}
{skill.details}
We can use each skill's id as a unique key. Refresh, and voila - no more errors.
Remember the
NewSkillcomponent?
app/assets/javascripts/components/newskill.js.jsx ``` var NewSkill = React.createClass({ render() { return (
What do we need to create a new skill? We need a form where the user can enter a name and details and a submit button which will take the input from the form and send it over to the API and add the skill to the database. Let's start with the form. We are just going to use regular HTML to get the form and the submit button on the page.
When we are submitting this new skill, we need to grab the text contents of the two input fields, the
name
and thedetails
, and store it in our database. In the earlier days of React, we could have used refs, but nowadays it's more common to use anonChange
handler and store the text on state. As you can see below, in theonChange
handlers we are executing an anonymous function which takes anevent
object as its argument, and then sets the state ofname
ordetails
to the current text value.
app/assets/javascripts/components/_new_skill.js.jsx
getInitialState() { return { name: '', details: '' } },
return (
Cool cool cool - but what happens when the user has entered a new skill and hits submit? Nothing. Let's add an event listener.
Submit
onClickis a React event listener, take a look at the docs to learn more about React events. We give the event listener some JavaScript code to evaluate whenever we click the button. Here, we are telling it to go execute the
handleClickfunction - which we haven't written yet.
// var NewSkill = ...handleClick() { console.log('in handle click!') },
// render()....
Check in the browser if it works and... great! Now, we need to fetch the form values and send it over to the server to create a new skill. Let's log the form values to be sure we have access to them.
var name = this.state.name; var details = this.state.details; console.log(name, details);
Let's send the form values over to the server so we can create a new skill.
handleClick() { var name = this.state.name; var details = this.state.details;$.ajax({ url: '/api/v1/skills', type: 'POST', data: { skill: { name: name, details: details } }, success: (response) => { console.log('it worked!', response); } }); },
We are making a POST request to '/api/v1/skills' and if it's successful we log the response. Did it work? Create a new skill in the browser and check the browser console. Refresh the page to make sure your newly created skill is rendered on the page.
But we don't want to refresh the page to see our new skills. We can do better.
We store all the skills we get from the server as state in
AllSkills. When we add a new skill, we could add it to the skills array so it will get rendered immediately with the other skills.
AllSkillsneeds to have access to the skills array and
NewSkillwants to update that array. Both children of
Bodyneed access to the skills array so we should store it as state in
Bodyand give both children access to it.
Let's move some code around. Move
getInitialState()and
componentDidMount()from
AllSkillsto
Body. Now, we fetch the skills when
Bodyis mounted on the DOM and we store them as state on the
Bodycomponent.
How does
AllSkillsget access to all the skills?
Parents can send variables down to their children as
props.
Propsare immutable in the child. Let's send the skills array from the
Bodycomponent to the
AllSkillscomponent as props.
app/assets/javascripts/components/_body.js.jsx
We have one more change to do before the skills will render on the DOM. In
AllSkillswe are iterating over
this.state.skillsto create DOM elements but we no longer have that state stored on the component.
AllSkillsreceives the skills as props from the parent, so instead of
this.state.skillswe need to ask for
this.props.skills.
app/assets/javascripts/components/allskills.js.jsx ``` var skills = this.props.skills.map((skill) => { return (
Level: {skill.level}
{skill.details}
Like we can pass down values from parents to children, we can also pass function references that can be executed in the child.
Let's starts from the
Body
. We want to build a function that's calledhandleSubmit()
that will add the new skill to the skills array.
app/assets/javascripts/components/_body.js.jsx
// getInitialState() and componentDidMount()
handleSubmit(skill) { console.log(skill); },
// renders the AllSkills and NewSkill component
Then, we want to send a reference to this function down to the
NewSkill
component.
```
In the
NewSkillcomponent, we can call this function by adding parenthesis, just like a regular JavaScript function. In the
successfunction, execute the
handleSubmitfunction and give it the name and details as an object as an argument.
app/assets/javascripts/components/newskill.js.jsx
$.ajax({ url: '/api/v1/skills', type: 'POST', data: { skill: { name: name, details: details } }, success: (skill) => { this.props.handleSubmit(skill); } });
Check your browser console to see if you get any output from
handleSubmitin the
Bodycomponent.
Almost there!
Now we need to add it to
this.state.skills. We can use
concat()to add the skill to the old state and then set the state with the new state.
app/assets/javascripts/components/_body.js.jsx
handleSubmit(skill) { var newState = this.state.skills.concat(skill); this.setState({ skills: newState }) },
That's it! We have successfully added a new skill that is rendered on the DOM immediately.
Here is the code for
Body,
AllSkillsand
NewSkillin case you want to check your code.
app/assets/javascripts/components/_body.js.jsx ``` var Body = React.createClass({ getInitialState() { return { skills: [] } },
componentDidMount() { $.getJSON('/api/v1/skills.json', (response) => { this.setState({ skills: response }) }); },
handleSubmit(skill) { var newState = this.state.skills.concat(skill); this.setState({ skills: newState }) },
render() { return (
app/assets/javascripts/components/_all_skills.js.jsx
var AllSkills = React.createClass({ render() { var skills = this.props.skills.map((skill) => { return (
Level: {skill.level}
{skill.details}
return ({skills})
} });
app/assets/javascripts/components/_new_skill.js.jsx
var NewSkill = React.createClass({ handleClick() { var name = this.state.name; var details = this.state.details;
$.ajax({ url: '/api/v1/skills', type: 'POST', data: { skill: { name: name, details: details } }, success: (skill) => { this.props.handleSubmit(skill); } });
},
render() { return (
8. Delete a skill
Ok, we can render skills and add new ones. Let's implement deleting skills so we can get rid of all the test skills we have added.
What do we need to do?
- Add a delete button to each skill
- Create a click event for the delete button that will travel up to
Body
- Remove the the skill from the skills array
- Update the state in
Body
with the new skills array- Make an Ajax call to our server to remove it from the database
Let's start with adding a delete button to each skill with an on click listener that takes us to the function
handleDelete
in the same component.
app/assets/javascripts/components/_all_skills.js.jsx
var AllSkills = React.createClass({ handleDelete() { console.log('in delete skill'); },
render() { var skills = this.props.skills.map((skill) => { return (
Level: {skill.level}
{skill.details}
Deletereturn ({skills})
}
});
```
Does it log to the browser console? Cool, we are good to go. Earlier I said that we were going to add a
Skillcomponent for each skill, but we aren't feeling any obvious pains from this setup, so let's keep it like it is.
The component needs to communicate with the parent and tell it to delete the idea that was clicked. Like we passed down a function
reference to
NewSkill, we are going to pass down a function reference that the child can execute when we click the
deletebutton.
app/assets/javascripts/components/_body.js.jsx ``` // getInitialState() and componentDidMount()
handleDelete() { console.log('in handle delete'); },
// render
```
Great! Now, we need to execute the function in the child when we hit the
handleDelete().
app/assets/javascripts/components/allskills.js.jsx ``` var AllSkills = React.createClass({ handleDelete() { this.props.handleDelete(); },
// render() ...
We have one pretty obvious problem to solve before we continue. How does the program know which skill it is that we want to delete? In the
Body
component we need to use some data that identifies the skill we want to remove so we can filter it out from the skills array. How about an id?If we use the skill id and pass it as an argument to
this.props.handleDelete()
we can easily filter the correct skill out by filtering out the skill with a matching id.Let's use our friend
bind()
- the first argument inbind()
is the value to be passed as thethis
value when the function is executed and consecutive arguments will be passed to the bound function as arguments.
app/assets/javascripts/components/_all_skills.js.jsx
handleDelete(id) { this.props.handleDelete(id); },
// iterate over the skills and create HTML elements
Delete
// render() etc
Now, in
handleDelete()
in theBody
component we need to use the id passed up from theAllSkills
component and remove the skill from the database using an Ajax call.
app/assets/javascripts/components/_body.js.jsx
handleDelete(id) { $.ajax({ url:
/api/v1/skills/${id}, type: 'DELETE', success(response) { console.log('successfully removed skill', response) } }); }, ```
Click
deleteand check in the console if it worked - you are awesome!
But... unless we refresh the page, the skill is still there. We aren't communicating to our view that the skill should be deleted.
Let's add a callback in the
success()function that removes the skill from the DOM.
app/assets/javascripts/components/_body.js.jsx ``
handleDelete(id) { $.ajax({ url:/api/v1/skills/${id}`, type: 'DELETE', success: () => { this.removeSkillFromDOM(id); } }); },
removeSkillFromDOM(id) { var newSkills = this.state.skills.filter((skill) => { return skill.id != id; });
this.setState({ skills: newSkills }); }, ```
Hop over to the browser and remove some skills... this is fantastic.
The last and final crud functionality. We are rendering all skills on the page, we are creating new ones, we are deleting them and now we just need to be able to edit them.
This is what we need to accomplish:
Editbutton
Editbutton
Edit, transform the text fields to input fields (alternatively render a new form below)
Submitbutton, grab the values from the input fields
Let's start with
1and
2. Add an
Editbutton and add a click listener for it which takes us to a
handleEditfunction in the same component.
app/assets/javascripts/components/allskills.js.jsx ``` // handleDelete()
handleEdit() { console.log('you are in edit!'); },
// render() and rest of the skill template
Edit ```
Do you get feedback in your browser console when we click
Edit? Cool.
What needs to happen in
handleEdit()? For the specific skill that the user asked to edit, add an edit form and var the user edit the values and then submit. If we were using jQuery, we could have just used jQuery's
$.append()function. However, as this StackOverflow succinctly puts it, it's not a React way. We should render components conditionally based on our state and props.
So if each skill needs to know whether or not its
Editbutton has been clicked (information which we should store as state), this seems like a good time to refactor out our current skill template in
AllSkillsto its own component.
$ touch app/assets/javascripts/components/_skill.js.jsx
We need to update
AllSkillsand create
Skillcomponents when we iterate over the
this.props.skills. Notice that we need to send the skill, and references to
handleDelete()and
handleEdit()as props to
Skill. This way we can access these values in
Skillusing the
this.props.*notation.
app/assets/javascripts/components/allskills.js.jsx ``` render () { var skills = this.props.skills.map((skill) => { return (
// return () the skills array } ```
In
Skillwe just return the entire template we removed from
AllSkills. Notice how we changed the JSX to comply with our new setup.
app/assets/javascripts/components/_skill.js.jsx ``` var Skill = React.createClass({ render() { return (
Level: {this.props.skill.level}
{this.props.skill.details}
Delete<button onclick="{this.props.handleEdit}">Edit</button>
} }); ```
Just to double check that we have wired things up correctly, go to the browser and make sure you can still delete skills and that something logs to the console when you click
Edit.
Now, when we click
Edit, we want to set a state that will tell us that we are editing the skill. Change the click listener for the
Editbutton so we land in a handler function in the current component,
Edit
and add that function in the
Skillcomponent.
handleEdit() { // something should happen here },
Now what? Add an initial state to the
Skillcomponent that defaults to
false. In
handleEdit()we need to set this state to true.
app/assets/javascripts/components/_skill.js.jsx ``` var Skill = React.createClass({ getInitialState() { return { editable: false } },
handleEdit() { this.setState({ editable: true }) },
// render() etc.. ```
And now what? We need to render the component conditionally based on our state. If
this.state.editableis false, we want to render
h3tag with the name and the
ptag with the details as normal. If not, we want to render an input field for the name and a textarea for the details. Sounds like we need ternary operator.
app/assets/javascripts/components/_skill.js.jsx ``` // getInitialState() and handleEdit()...
render() { var name = this.state.editable ? :
var details = this.state.editable ? :
{this.props.skill.details}
return (Level: {this.props.skill.level}
{details} DeleteEdit
) } }); ```
In the render function we are using a ternary to decide how we should render name/details. It doesn't matter what data we give our component, based on its state, props and the constraints we set up, we always know what the component will render. We want dumb child components that just render conditionally based on the props they receive and their current state. Head over to the browser and check it out!
Let's transform the
Editbutton to a
Submitbutton when we click
Edit. We can use the
editablestate and a ternary directly in the JSX to change that.
app/assets/javascripts/components/_skill.js.jsx
{this.state.editable ? 'Submit' : 'Edit' }
Awesome.
We can make a small change to how we update the state in
handleEdit()to make it toggle between true/false.
handleEdit() { this.setState({ editable: !this.state.editable }) },
But now, when we click
Submit, we need to fetch the updated values and send them over to the server to update the given skill. We can do this using the same strategy we deployed in
_new_skill.js.jsx. Let's add the
onChangecallback to the input field and the textarea in
Skill(forgot to carry those over when we extracted the skill to its own component).
getInitialState() { return { name: '', details: '' } },....
var name = this.state.editable ? this.setState({ name: e.target.value }) } defaultValue={this.props.skill.name} /> :
{this.props.skill.name}
var details = this.state.editable ? this.setState({ details: e.target.value }) } defaultValue={this.props.skill.details}> :
{this.props.skill.details}
There are no strict rules on how you choose to format ternaries. The most important thing is to make it readable for future you and other developers.
Let's add some code to
handleEdit().
if (this.state.editable) { var name = this.state.name; var details = this.state.details; console.log('in handleEdit', this.state.editable, name, details); this.onUpdate(); }this.setState({ editable: !this.state.editable })
What are we trying to find out here? When we hit this function and
this.state.editableis true, meaning if we are currently editing the text, we want to grab the name and the details and log them to the browser console. Then, we simply toggle the state to alternate between true/false. Try it out in the browser and make sure it's behaving as expected.
Cool. Let's walk up the chain, from
Skillto
AllSkillsto
Bodyand update the specific skill in the
Bodycomponent. Why update the skill in the
Bodycomponent and not right away in the
Skillcomponent? Because we store all skills as state in the
Bodycomponent and data should be updated in one place.
Fetch the values, compose a skill object and trigger the chain by executing the
handleUpdate()function reference passed down by the parent.
app/assets/javascripts/components/_skill.js.jsx ``` onUpdate() { if (this.state.editable) { var name = this.state.name; var details = this.state.details; var skill = { name: name, details: details }
this.props.handleUpdate(skill);
} this.setState({ editable: !this.state.editable }) }, ```
This component is just passing it up to its parent.
app/assets/javascripts/components/allskills.js.jsx ``` onUpdate(skill) { this.props.handleUpdate(skill); },
render() { var skills = this.props.skills.map((skill) => { return (
This is the end of the chain and where we use the
skillobject passed up to update the state,
this.state.skills.
app/assets/javascripts/components/_body.js.jsx ``` handleUpdate(skill) { console.log(skill, 'in handleUpdate'); },
render() { return (
Since
this.state.skillsis an array of objects it makes most sense to just swap out entire objects instead of opening one up and updating single properties on that object. Let's update the object we pass up from
Skillto look more like the objects we store as state in
Body.
var id = this.props.skill.id; var name = this.state.name; var details = this.state.details; var level = this.props.skill.level;var skill = {id: id, name: name, details: details, level: level }
In
handleUpdate()in the
Bodycomponent we need to swap out the old object with the new one - and make an Ajax call to update the database.
handleUpdate(skill) { $.ajax({ url: `/api/v1/skills/${skill.id}`, type: 'PUT', data: { skill: skill }, success: () => { console.log('you did it'); this.updateSkills(skill); // callback to swap objects } }); },
And now let's write the callback that will swap out the objects.
handleUpdate(skill) { // ajax stuffs success: () => { this.updateSkills(skill) } }); },updateSkills(skill) { var skills = this.state.skills.filter((s) => { return s.id != skill.id }); skills.push(skill);
this.setState({ skills: skills }); },
First we filter out the skill that matches
skill.id, then we are pushing the updated skill onto the filtered skills array and then we are updating the state with the correct values.
Last thing we will do before we see if there are any opportunities to refactor our code is updating the level of a skill. Either we could have three buttons corresponding to each of the levels (bad, half-bad and fantastic), or, we could have an up arrow and a down arrow and when the user clicks either it levels up and down respectively.
It seems like implementing the arrows will take slightly more work, so let's do that.
First, we need our arrow buttons - and we'll be adding our first css!
$ touch app/assets/stylesheets/skills.scss
app/assets/stylesheets/application.scss
@import "skills";
app/assets/stylesheets/skills.scss ``` .skill-level { display: inline-flex; }
.skill-level button { background-color: pink; border: 1px solid deeppink; } ```
Wrap the
levelwith the arrow buttons.
app/assets/components/javascripts/_skill.js.jsx ```
Level: {this.props.skill.level}
Let's write down a todo-list for this feature.
For #3 we can use the same chain we used for editing the name and the details (
this.props.handleUpdate()).
Let's add a click listener for both arrow buttons and bind arguments to them.
app/assets/components/javascripts/_skill.js.jsx ```
Level: {this.props.skill.level}
Now we need logic in
handleLevelChange()
to decide whether or not to update the level when we click either button.
app/assets/components/javascripts/_skill.js.jsx
handleLevelChange(action) { var levels = ['bad', 'halfbad', 'fantastic']; var name = this.props.skill.name; var details = this.props.skill.details; var level = this.props.skill.level; var index = levels.indexOf(level);
if (action === 'up' && index < 2) { var newLevel = levels[index + 1]; this.props.handleUpdate({id: this.props.skill.id, name: name, details: details, level: newLevel}) } else if (action === 'down' && index > 0) { var newLevel = levels[index - 1]; this.props.handleUpdate({id: this.props.skill.id, name: name, details: details, level: newLevel}) } },
That code is working. It's not pretty, but it's working.
I'm going to keep it like this and deal with it first thing in next section - time to refactor!
11. Refactor
To refactor the code above, it's a good start to try to state what is happening in the function.
'If the level can be changed, send the updated object up the chain to be updated'.
That gave me this:
app/assets/components/javascripts/_skill.js.jsx
handleLevelChange(action) { if (this.levelCanBeChanged(action)) { var skill = this.updatedSkill() this.props.handleUpdate(skill); } },
this.levelCanBeChanged(action)
will return either true or false. We send it the action, either 'up' or 'down', and checks the given limit meets a condition.app/assets/components/javascripts/_skill.js.jsx
handleLevelChange(action) { var levels = ['bad', 'halfbad', 'fantastic']; var level = levels.indexOf(this.props.skill.level);
if (this.levelCanBeChanged(action, level)) { var skill = this.updatedSkill() this.props.handleUpdate(skill); } },
levelCanBeChanged(action, limit) { return action === 'up' && limit < 2 || action === 'down' && limit > 0; }, ```
Next up is
updatedSkill(). We return an object with an updated level that is set by checking the action and moving either up or down in an array.
app/assets/components/javascripts/_skill.js.jsx ``` updatedSkill(action, index) { var id = this.props.skill.id; var name = this.props.skill.name; var details = this.props.skill.details;
var levels = ['bad', 'halfbad', 'fantastic']; var change = action === 'up' ? 1 : - 1; var newLevel = action ? levels[index + change] : this.props.skill.level;
return {id: id, name: name, details: details, level: newLevel} }, ```
We can also refactor out the part where we set the new level to a function.
app/assets/components/javascripts/_skill.js.jsx ``` getNewLevel(action, index) { var levels = ['bad', 'halfbad', 'fantastic']; var change = action === 'up' ? 1 : - 1;
return action ? levels[index + change] : this.props.skill.level; }, ```
This looks better, but there is more to do in this component.
onUpdate()can be made better. Let's make it a bit more readable.
app/assets/components/javascripts/_skill.js.jsx ``` onUpdate() { if (this.state.editable) { var skill = { id: this.props.skill.id, name: this.state.name, details: this.state.details, level: this.props.skill.level }
this.props.handleUpdate(skill);
}
this.setState({ editable: !this.state.editable }) }, ```
The handler function for the level change,
onLevelChange, can be renamed to
onUpdateLevelto better match the naming pattern we have for the editing handler function. To make the following code working below I had to update the implemenation of
this.props.handleUpdate,
handleUpdate()in the
Bodycomponent. In this function we are now only passing up the attributes we need to update (we need the id for the Ajax call). We can therefore also drop the
levelattribute in the skill object in
onUpdate().
app/assets/components/javascripts/_skill.js.jsx ``` onUpdateLevel(action) { if (this.canChangeLevel(action)) { var level = this.getNewLevel(action) var skill = {id: this.props.skill.id, level: level }
this.props.handleUpdate(skill);
} }, ```
Since we are no longer passing up a full skill object we can no longer use it to update the skill in
updateSkills(). Instead, we need our API to pass the updated object back so we can keep replacing the old skill with the new skill in
updateSkills. Otherwise we would have to update only the attributes that were present in the skill object which feels... a bit strange. Also, it's way safer to use the updated object from our API and if we can, we wouldn't we?
app/assets/javascripts/components/_body.js.jsx ``
handleUpdate(skill) { $.ajax({ url:/api/v1/skills/${skill.id}`, type: 'PUT', data: { skill: skill }, success: (skill) => { this.updateSkills(skill) } }); },
app/skills/controllers/api/v1/skills_controller.rb
def update skill = Skill.find(params["id"]) skill.updateattributes(skillparams) respond_with skill, json: skill end ```
Our next step is to filter skills based on the level. Our goal is to create a select input that has an option for each level. When the select input is changed it will show only the skills at the selected level to the user. For example, if the user wants to review the 'halfbad' skills they would select 'halfbad' from our soon to be created dropdown and without having to refresh the page, we would want only the skills with a level of 'halfbad' to show up in our
AllSkillscomponent.
First let's create a SelectFilter component.
touch app/javascripts/components/_select_filter.js.jsxIn our
_select_filterwe will create a component that has a selector and label. Our
SelectFilterclass renders a Label, and a Select input with four options (all, bad, halfbad, and fantastic).
app/assets/components/javascripts/selectfilter.js.jsx
var SelectFilter = React.createClass({ render (){ return(All Bad Halfbad Fantastic) } }
To make sure the
SelectFiltercomponent looks the way we want, we will add it to the
Bodycomponent in our
_body.js.jsxfile, fire up the server (if you haven't yet done so) with
rails s, and then navigate to
localhost:3000.
app/assets/components/javascripts/_body.js.jsx
render() { return (If everything is wired up correctly, you should now see a select input with the four options in between the) }
NewSkillform and the
AllSkillslist.
Now we will actually create our filtering functionality. The big picture is that we want to filter based on the level, so we will start our journey by passing a
handleFilterproperty to our
SelectFiltercomponent. This property we will call whenever we want to actually filter our skills, so we need to assign it a callback -
this.filterSkillsByLevel.
app/assets/components/javascripts/_body.js.jsx
render() { return () }
handleFilterproperty we have a function called
filterSkillsByLevel, so let's go ahead and create that within our
_body.js.jsx.
app/assets/components/javascripts/_body.js.jsx
filterSkillsByLevel(level) { console.log("about to filter"); },We will add the functionality of filtering in the above
filterSkillsByLevel(level)function. But first, let's wire it all together and make sure that when the user changes the select dropdown, this
filterSkillsByLevelfunction is invoked.
Let's add an
onChangeevent to our select input that will call the
updateFilterfunction. In order to accomplish that we must bind the object 'this' to our function call. In this case, the 'this' object refers to the
SelectFiltercomponent. This is important because if we did not bind 'this', when we get into the updateFilter function call we would not be able to call
this.stateor
this.propssince in that case, this would refer to the function
updateFilter, not the component
SelectFilter. That is a lot of this's and thats and for what its worth, this is probably the toughest part of React!
app/assets/components/javascripts/selectfilter.js.jsx ``` render (){ return(