A React component can be defined as an ES6 class that extends the base React.Component
class. In its minimal form, a component must define a render
method that specifies how the component renders to the DOM. The render
method returns React nodes, which can be defined using JSX syntax as HTML-like tags. The following example shows how to define a minimal Component:
import React from 'react'
class HelloWorld extends React.Component {
render() {
return <h1>Hello, World!</h1>
}
}
export default HelloWorld
A Component can also receive props
. These are properties passed by its parent in order to specify some values the component cannot know by itself; a property can also contain a function that can be called by the component after certain events occur - for example, a button could receive a function for its onClick
property and call it whenever it is clicked. When writing a component, its props
can be accessed through the props
object on the Component itself:
import React from 'react'
class Hello extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>
}
}
export default Hello
The example above shows how the component can render an arbitrary string passed into the name
prop by its parent. Note that a component cannot modify the props it receives.
A component can be rendered within any other component, or directly into the DOM if it's the topmost component, using ReactDOM.render
and providing it with both the component and the DOM Node where you want the React tree to be rendered:
import React from 'react'
import ReactDOM from 'react-dom'
import Hello from './Hello'
ReactDOM.render(<Hello name="Billy James" />, document.getElementById('main'))
By now you know how to make a basic component and accept props
. Lets take this a step further and introduce state
.
For demo sake, let's make our Hello World app, display only the first name if a full name is given.
import React from 'react'
class Hello extends React.Component {
constructor(props){
//Since we are extending the default constructor,
//handle default activities first.
super(props);
//Extract the first-name from the prop
let firstName = this.props.name.split(" ")[0];
//In the constructor, feel free to modify the
//state property on the current context.
this.state = {
name: firstName
}
} //Look maa, no comma required in JSX based class defs!
render() {
return <h1>Hello, {this.state.name}!</h1>
}
}
export default Hello
Note: Each component can have it's own state or accept it's parent's state as a prop.