Write first React component

Buman-Erdene Usukhbayar (Eny)
3 min readSep 3, 2018

--

React isn’t too much different from your base knowledge which is HTML and JS, therefore maybe easy to learn but there is a few syntax you must firstly know.

Component structure

Component structure

As you see there is a constructor and local state/can be all of type/ and only one render function and it’s included one return element. Inside the return all element must surrounding one element. That’s the base structure.

All below examples are part of 1 code.

Component without constructor and state, called 2 children component Button and AnotherBtn

If your code isn’t complex as above section, it can be possible you can create component without constructor and state. Why? because you don’t need to use data from parent component. Another word if your component receive data from parent component you will use constructor.

<Button/> and <AnotherBtn/> is child component. Inside name and className are properties.

Constructor can be without state, state can’t be without constructor.

Button component

In this component’s render section shows us 1 button element. {this.props.name} receive data from their parent component. Also in this section used local state.

In React we use className instead class.

Arrow function

You can define your component by function. Why again? Because if you decide this component no need to use local state it can be forever like this :). No use this key word in this case. What is {anotherBtn}? In React className and other names are camelCase. anotherBtn is variable AnotherBtn is component.

Inline style

In React can be write inner style by variable. There is a few rules used in this case.

  1. No hyphens no background-color, yes backgroundColor.
  2. No just none, yes ‘none’.
  3. No 1em, yes ‘1em’ or 1
  4. No ; yes , :)
  5. No red, yes ‘red’

Now you can:

  1. write component
  2. call children component inside your main component
  3. pass props(data) to children component
  4. add little bit style
Render to HTML page

Last one is render to HTML page for your component. First section must parent component, and second section must your html element want to render. Full example is here.

Hope this helpful to write your first React component!

--

--

Buman-Erdene Usukhbayar (Eny)
Buman-Erdene Usukhbayar (Eny)

Written by Buman-Erdene Usukhbayar (Eny)

SWE, You'll find pretty much random stories.

No responses yet