Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

By clicking text how to change clicked text to another text in React.js

Tags:

text

reactjs

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?

comment and title

like image 872
Feruza Avatar asked Apr 26 '17 10:04

Feruza


2 Answers

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>;
}
like image 190
Valentin Duboscq Avatar answered Oct 24 '22 15:10

Valentin Duboscq


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'/>
like image 33
Bhavya Sinha Avatar answered Oct 24 '22 15:10

Bhavya Sinha