claudiopb
claudiopb

Reputation: 1100

ReactJS - Function to be implemented in a lot of components

In this component i'm using the noMoreLonelyWords() utilitarian function which is working good. It's objective is to render the paragraph without single word in the last line, like this example:

enter image description here

import React, { Component } from 'react';
import Column1 from './Column1'
import Column2 from './Column2'
import FooterMobile from './FooterMobile'

class App extends Component {
  constructor(props) {
    super(props)     
    this.noMoreLonelyWords = this.noMoreLonelyWords.bind(this)
  }


  noMoreLonelyWords = (selector, numWords) => {      
    var elems = document.querySelectorAll(selector);
    var i;
    for (i = 0; i < elems.length; ++i) { 
      var textArray = elems[i].innerText.split(" ");      
      var lastWords = textArray.splice(-numWords, numWords).join("&nbsp;");     
      var textMinusLastWords = textArray.join(" ");
      elems[i].innerHTML = textMinusLastWords + " " + lastWords;
    }
}

componentDidUpdate(){   
  this.noMoreLonelyWords("p", 2)
}

  render() {
    return (
      <div>        
        <div className="wrapper-all">
          <Column1 />
          <Column2 />
          <FooterMobile />
        </div>    
      </div>
    )
  }
}


export default App;

My question is that this function will be used by multiple child components that contains paragraph. That's why I wanted to know the best way to implement it.

Upvotes: 1

Views: 38

Answers (1)

klugjo
klugjo

Reputation: 20885

Create a utilities.js file and put

  export const noMoreLonelyWords = (selector, numWords) => {      
    var elems = document.querySelectorAll(selector);
    var i;
    for (i = 0; i < elems.length; ++i) { 
      var textArray = elems[i].innerText.split(" ");      
      var lastWords = textArray.splice(-numWords, numWords).join("&nbsp;");     
      var textMinusLastWords = textArray.join(" ");
      elems[i].innerHTML = textMinusLastWords + " " + lastWords;
    }
  }

Then in your components import it using

import {noMoreLonelyWords} from 'path/to/utilities';

and use it directly, example:

componentDidUpdate(){   
  noMoreLonelyWords("p", 2)
}

Upvotes: 2

Related Questions