Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interacting with React components from non-react world

Tags:

reactjs

We've an application that already uses KnockoutJS extensively. For Charting we are planning to use ReactJS. We could able to build simple charts with ReactJS easily. One of the question that puzzle my how can I interact with this React charts from a non-React world. Let me put an example. Let's say you've a bar chart React component and initially you want to render the chart with axes and so you do like below.

ReactDOM.render(<BarChart axes={true} data={data} {...lot of other props} />, mountNode);

Now let's assume you've a button that exists in a non-React world and on click of the button you want to hide the axes. How can I do that? Can I able to expose a public method in the BarChart component that can be invoked from outside?

For ex.,

const BarChart = React.createClass({

   ....

   showAxes(show) {
     //...
   }
});

var barChart = ReactDOM.render(<BarChart axes={true} data={data} {...lot of other props} />, mountNode);
barChart.showAxes(false);

But the axes is a prop not state and so even we expose a public method we cannot change the prop right? Any ideas how we can handle these things? How we can interact with React components from an non-react world?

like image 767
VJAI Avatar asked Jul 08 '16 06:07

VJAI


People also ask

Is it possible to use React without JSX?

JSX is not a requirement for using React. Using React without JSX is especially convenient when you don't want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React.

Is it possible to integrate third party libraries with React?

React can be used in any web application. It can be embedded in other applications and, with a little care, other applications can be embedded in React.

How do you connect components in React?

The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.


1 Answers

You are right just expose the function and call the function from outside. You can store axes in state in the getinitialState

const BarChart = React.createClass({
   getInitialState(){
    return {
        axes: this.props.axes
     }
  }
   ....

   showAxes(show) {
     //...
     this.setState({
        axis: show
     })
   }
});

var barChart = ReactDOM.render(<BarChart axes={true} data={data} {...lot of other props} />, mountNode);
barChart.showAxes(false);
like image 85
Piyush.kapoor Avatar answered Oct 10 '22 04:10

Piyush.kapoor