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>;
}
Either you can store the text in state
variable and onClick
of text update the state
value, or maintain a bool
in state
whether the text has been clicked or not, if yes then show first text otherwise another one,
Try this by storing the text in state
:
class App extends React.Component{
constructor(){
super();
this.state= {title: 'Click text'}
}
render(){
return <div onClick= {() => this.setState({title:'New text'})}>{this.state.title}</div>
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
Try this by using a bool
in state
variable:
class App extends React.Component{
constructor(){
super();
this.state= {clicked: true}
}
render(){
return <div onClick= {() => this.setState({clicked: !this.state.clicked})}>
{
this.state.clicked? 'First Text' : 'Second Text'
}
<br/>
* click on text to toggle
</div>
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With