3

I have converted a component that displays chart bar, and it requires this js snippet to run, what is the correct way of integrating it inside my JSX code?

<script>
    /** START JS Init "Peity" Bar (Sidebars/With Avatar & Stats) from sidebar-avatar-stats.html **/
    $(".bar.peity-bar-primary-avatar-stats").peity("bar", {
        fill: ["#2D99DC"],
        width: 130,
    })
</script>

I have seen this libraries on npm website, but they mostly deal with external scripts not internal

here is my component:

import React, { Component } from 'react';

export default class App extends Component {
  render() {
    return (
    <div>
          "How can I render js code here?" 
     </div>
    );
  }
}

2 Answers 2

3

You can use refs and componentDidMount callback in order to initialize jquery plugins, like so

class App extends React.Component {
  
  componentDidMount() {
    $(this.barChart).peity("bar", { 
      fill: ["#2D99DC"], width: 130
    });
  }
  
  render() {
    return <div>
      <div ref={ (node) => { this.barChart = node }  }>
        <span class="bar">5,3,9,6,5,9,7,3,5,2</span>
        <span class="bar">5,3,2,-1,-3,-2,2,3,5,2</span>
        <span class="bar">0,-3,-6,-4,-5,-4,-7,-3,-5,-2</span>
      </div>  
    </div>;
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/peity/3.2.1/jquery.peity.js"></script>
<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="container"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

You should use componentDidMount lifecycle hook. Add this to your component code:

componentDidMount() {
 $(".bar.peity-bar-primary-avatar-stats").peity("bar", {
        fill: ["#2D99DC"],
        width: 130,
    })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.