Reputation: 10690
I have a web application written in classic HTML/CSS/jQuery. I am writing a chat overlay (similar to the Facebook chat overlay) which needs to be highly interactive. I initially wrote this using Vue, but I decided to try re-writing it using React for learning purposes and I'm stuck at one particular part.
I have a component called ChatOverlay
, which handles all of the conversations that should be displayed on the page. I render this ChatOverlay in a div with id='chat-footer'
, which is just a fixed element overlaying the page.
const element = <ChatOverlay name="Testing" conversationId="a6b9bc89-b9ff-4eb1-86d8-ac5986fb5cbe"/>;
ReactDOM.render(
element,
document.getElementById('chat-footer')
);
However, I'm not sure how to interact with the React components from outside the react "environment". For example, I may have a button on the a user's profile which says "chat". For example, consider the following jquery click event handler:
$('.chat-button').on('click', function(){
//I need to tell the react app to open another conversation
});
With Vue, in the click handler, I could easily call a Vue function which can perform some actions in Vue's "environment", however I'm not sure how to achieve the same thing in React. Any advice would be much appreciated.
Upvotes: 1
Views: 98
Reputation: 10690
I was able to solve this by doing the following. I realized the ReactDOM.render actually returns an instance of the ChatOverlay component which I can then access from anywhere else in my JS code. I'm not sure if this is the best way to achieve this, but it seems to work for me.
const element = <ChatOverlay />;
let chatOverlay = ReactDOM.render(
element,
document.getElementById('chat-footer')
);
$('.chat-button').on('click', function(){
chatOverlay.openChat()
});
Upvotes: 1
Reputation: 13
I'm pretty new to React too. I think you use the onClick property to call the function. Something like this. I may be misunderstanding your question though, and I may just be flat out wrong. Either way, Happy Thanksgiving.
import React, { Component } from 'react'
class CHAT-OVERLAY extends Component {
const myFunction = (event) => {
// your function stuff
}
render(){
return(
<button
className='chat-button'
onClick={this.myFunction}
> Chat Button
</ button>
)
}
}
export default CHAT-OVERLAY
Upvotes: 0
Reputation: 1103
ReactJs is descriptive and explicit about what and how things work. To set an action on a button, the action should be set when you define the button, not somewhere else in the program.
<button className='chat-button' onClick={()=>{
//I need to tell the react app to open another conversation
props.openAnotherConversation()
} value='Open Convo' />
You can also use ref={(node)=>{this.buttonRef=node}}
if you have a need to do HTMLDom like references to the button as a HTML object.
Upvotes: 0