I am new in React.js and could not find any answer to this question.
I have a blog for commentaries, and when I click on the title of a comment, the title should change to another text. How would I do that?
You can use onClick
function and store your title in a state variable.
Here is an example :
class Title extends Component {
constructor() {
super();
this.state() {
title: "Click here"
}
}
changeTitle = () => {
this.setState({ title: "New title" });
};
render() {
return <h1 onClick={this.changeTitle}>{this.state.title}</h1>;
}
}
You can find more examples here : Handling Events - React
Update : You can now use Hooks with React 16.8
import React, { useState } from "react";
const Title = () => {
const [title, setTitle] = useState("Click here");
return <h1 onClick={() => setTitle("New title")}>{title}</h1>;
}