This is the app we are going to build. Two buttons that change the case of a text. Pretty simple but good enough to look at a few of React’s basic syntax.
Let’s get started by creating a simple HTML document and include the React libraries. You will also need to include a script tag and create div with
id="main"in the the document body.
Make sure you are using the latest version of React. At the time of writing, this is what I have in my index.html:
Note: It is
possible recommended to use React with a CommonJS module system like browserify or webpack and to install it with npm.
(The babel-core library we have included, allows in browser JSX transformation and the use of
<script type="text/babel"> tags.)
Let’s create a button component on our page with React:
React.createClass()to declare new components.
- A React Class should have a
renderfunction that returns the element’s HTML. Careful to use
return(<HtmlTag />)and not
- ReactDOM.render() is our app’s main entry point and renders our components. The first argument is the
<ReactTag />that we declared with
createClass()and the second is the HTML element that will contain the rendered React component.
- React classes should always start with an Capital letter.
Check out the code here: https://jsbin.com/xakiza/edit?html,output
It is possible to pass arguments to components using components properties.
Change your React code to:
- Pass an argument by adding a property like you would in HTML. In this example, we added the
- In the component definition, use
this.props.propertyNameto access the value passed to that component.
Check out the code here: https://jsbin.com/qakaka/edit?html,output
We are now going to create a
<Main /> component to hold our button and text. This component will hold our application’s state.
Our code is getting larger, here are the main things to pay attention to:
- We now have 3 components (Main, UppercaseButton and HelloText). Main holds UppercaseButton and HelloText.
getInitialState()is a special React function that will be called once when a component is initialized. Make use of it to return the initial state object.
- The component state can be access with
- The component state can be modified using
- To set a inline style using the JSX syntax, use
Check out the code and play around here: https://jsbin.com/beheve/edit?html,output
Let’s now add our second button by creating a generic button.
clickHandlerfunction is now generic.
- The child components (buttons here) will decide what to send to the
Check out the final code here: https://jsbin.com/bidafa/edit?html,output
Hopefully this quick first look at React will help you get started and get an idea of the framework’s potential.