By clicking text how to change clicked text to another text in React.js
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'/>
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>;
}