React JS for Beginners

React JS

Is React JS a Library or a Framework?

What is a Library?

What is a Framework?

The setup

Components

class Hello extends React.Component {
render() {
return <h1>Hello world!</h1>;
}
}
ReactDOM.render(
<Hello />,
document.getElementById("root")
);

So we’re simply saying: Hey React! Please render the Hello component inside the DOM node with an id of root!

class Hello extends React.Component {
render() {
return <h1>Hello world!</h1>;
}
}
ReactDOM.render(
<Hello />,
document.getElementById("root")
);

So we’re simply saying: Hey React! Please render the Hello component inside the DOM node with an id of root!

Handling data

Props

ReactDOM.render(
<Hello message="my friend" />,
document.getElementById("root")
);
class Hello extends React.Component {
render() {
return <h1>Hello {this.props.message}!</h1>;
}
}

State

Initializing state

class Hello extends React.Component {

constructor(){
super();
this.state = {
message: "my friend (from state)!"
};
}

render() {
return <h1>Hello {this.state.message}!</h1>;
}
}

Changing the state

class Hello extends React.Component {

constructor(){
super();
this.state = {
message: "my friend (from state)!"
};
this.updateMessage = this.updateMessage.bind(this);
} updateMessage() {
this.setState({
message: "my friend (from changed state)!"
});
}
render() {
return <h1>Hello {this.state.message}!</h1>;
}
}

Note: To make this work, we also had to bind the this keyword to the updateMessage method. Otherwise we couldn’t have accessed this in the method.

Event Handlers

render() {
return (
<div>
<h1>Hello {this.state.message}!</h1>
<button onClick={this.updateMessage}>Click me!</button>
</div>
)
}
class Hello extends React.Component {

constructor(){
super();
this.state = {
message: "my friend (from state)!"
};
this.updateMessage = this.updateMessage.bind(this);
} updateMessage() {
this.setState({
message: "my friend (from changed state)!"
});
} render() {
return (
<div>
<h1>Hello {this.state.message}!</h1>
<button onClick={this.updateMessage}>Click me!</button>
</div>
)
}
}

--

--

3rd Year Software Engineering Undergraduate

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store