When clicking on text, how to change the text that was clicked to another text in React.js
You can use onClick
and store your title in a state variable.
Here's 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: Event Handling - React
Update: you can now use hooks since React 16.8
import React, { useState } from "react";
const Title = () => {
const [title, setTitle] = useState("Click here");
return <h1 onClick={() => setTitle("New title")}>{title}</h1>;
}
source to share
Either you can store the text in a variable state
and onClick
text, update the value state
, or store bool
in state
whether the text was clicked or not, if yes then show the first text otherwise different,
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 with a variable bool
in state
:
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'/>
source to share
Please feel free to copy all mine below, which is a fully tested source (which has everything like defaultProps):
import React, {Component} from 'react';
export default class InterchangeableText extends Component {
constructor(props) {
super(props);
this.state = {
title: this.props.defaultText
}
this.changeTitle = this.changeTitle.bind(this);
}
changeTitle() {
this.setState({
title: this.props.changedText
});
}
render() {
return <div onClick={this.changeTitle}>{this.state.title}</div>;
}
}
InterchangeableText.defaultProps = {
defaultText: 'defaultText',
changedText: 'changedText'
}
Next, in another component where you render the above component, add:
// ...
render() {
return <InterchangeableText defaultText="some default text" changedText="text changed!"/>
}
source to share