### Install react-websocket using npm Source: https://github.com/mehmetkose/react-websocket/blob/master/README.md This command installs the react-websocket package as a dependency for your project. Ensure you have Node.js and npm installed. ```bash npm install --save react-websocket ``` -------------------------------- ### Specify WebSocket Protocol with react-websocket Source: https://context7.com/mehmetkose/react-websocket/llms.txt This example shows how to specify a WebSocket subprotocol using the 'protocol' prop. This is useful for servers that require specific protocol negotiation, such as 'graphql-ws'. It includes basic message handling and connection event callbacks. ```jsx import React from 'react'; import Websocket from 'react-react-websocket'; class SecureDataStream extends React.Component { handleData(data) { console.log('Received:', data); } render() { return (
console.log('Protocol negotiated')} onError={(e) => console.error('Connection failed:', e)} reconnect={true} debug={false} />
); } } export default SecureDataStream; ``` -------------------------------- ### react-websocket Component Props Reference Source: https://context7.com/mehmetkose/react-websocket/llms.txt This snippet provides a comprehensive reference for the react-websocket component's props. It lists required and optional props, their types, default values, and usage examples, including 'url', 'onMessage', 'onOpen', 'onClose', 'onError', 'debug', 'reconnect', 'protocol', and 'reconnectIntervalInMilliSeconds'. ```jsx import React from 'react'; import Websocket from 'react-websocket'; import PropTypes from 'prop-types'; // Full props example with all options console.log(data)} // Required: Message handler callback onOpen={() => console.log('Connected')} // Optional: Connection opened callback onClose={(code, reason) => {}} onError={(error) => console.error(error)} // Optional: Error handler callback debug={false} // Optional: Enable console logging (default: false) reconnect={true} // Optional: Auto-reconnect on disconnect (default: true) protocol='wamp' // Optional: WebSocket subprotocol reconnectIntervalInMilliSeconds={3000} // Optional: Fixed reconnect interval (default: exponential backoff) /> // PropTypes definition for reference: // Websocket.propTypes = { // url: PropTypes.string.isRequired, // onMessage: PropTypes.func.isRequired, // onOpen: PropTypes.func, // onClose: PropTypes.func, // onError: PropTypes.func, // debug: PropTypes.bool, // reconnect: PropTypes.bool, // protocol: PropTypes.string, // reconnectIntervalInMilliSeconds: PropTypes.number // }; ``` -------------------------------- ### Basic Usage of react-websocket Component Source: https://github.com/mehmetkose/react-websocket/blob/master/README.md This JavaScript code demonstrates how to integrate the react-websocket component into a React application. It sets up a websocket connection and handles incoming messages to update the component's state. Requires React and the react-websocket library. ```javascript import React from 'react'; import Websocket from 'react-websocket'; class ProductDetail extends React.Component { constructor(props) { super(props); this.state = { count: 90 }; } handleData(data) { let result = JSON.parse(data); this.setState({count: this.state.count + result.movement}); } render() { return (
Count: {this.state.count}
); } } export default ProductDetail; ``` -------------------------------- ### Websocket Component: Establish and Manage Connections in React Source: https://context7.com/mehmetkose/react-websocket/llms.txt Demonstrates how to use the Websocket component to establish a WebSocket connection in a React application. It includes callbacks for handling incoming messages, connection open/close events, and errors. The component manages the WebSocket lifecycle and provides reconnection capabilities. ```jsx import React from 'react'; import Websocket from 'react-websocket'; class ProductDetail extends React.Component { constructor(props) { super(props); this.state = { count: 90, connected: false }; } handleData(data) { let result = JSON.parse(data); this.setState({ count: this.state.count + result.movement }); } handleOpen() { this.setState({ connected: true }); console.log('WebSocket connected'); } handleClose(code, reason) { this.setState({ connected: false }); console.log(`WebSocket disconnected: ${code} - ${reason}`); } handleError(error) { console.error('WebSocket error:', error); } render() { return (

Status: {this.state.connected ? 'Connected' : 'Disconnected'}

Count: {this.state.count}

); } } export default ProductDetail; ``` -------------------------------- ### Websocket Component: Send Messages in React Source: https://context7.com/mehmetkose/react-websocket/llms.txt Illustrates how to send messages through a WebSocket connection using the react-websocket component. It shows how to access the component's instance via a ref to call the `sendMessage` method. This is useful for interactive applications like chat. ```jsx import React from 'react'; import Websocket from 'react-websocket'; class ChatApp extends React.Component { constructor(props) { super(props); this.state = { messages: [], inputValue: '' }; } handleData(data) { const message = JSON.parse(data); this.setState(prevState => ({ messages: [...prevState.messages, message] })); } sendMessage() { if (this.refWebSocket && this.state.inputValue) { const payload = JSON.stringify({ text: this.state.inputValue, timestamp: Date.now() }); this.refWebSocket.sendMessage(payload); this.setState({ inputValue: '' }); } } render() { return (
{this.state.messages.map((msg, i) => (

{msg.text}

))}
this.setState({ inputValue: e.target.value })} /> { this.refWebSocket = Websocket; }} />
); } } export default ChatApp; ``` -------------------------------- ### Configure Reconnection with react-websocket Source: https://context7.com/mehmetkose/react-websocket/llms.txt This snippet demonstrates how to configure automatic WebSocket reconnection using the 'reconnect' prop and set a custom interval with 'reconnectIntervalInMilliSeconds'. It also shows basic event handling for message reception, connection opening, and closing, including tracking reconnection attempts. ```jsx import React from 'react'; import Websocket from 'react-websocket'; class RealTimeData extends React.Component { constructor(props) { super(props); this.state = { data: null, connectionAttempts: 0 }; } handleData(data) { this.setState({ data: JSON.parse(data) }); } handleOpen() { console.log('Connected to data stream'); this.setState({ connectionAttempts: 0 }); } handleClose(code, reason) { this.setState(prevState => ({ connectionAttempts: prevState.connectionAttempts + 1 })); console.log(`Disconnected. Attempt #${this.state.connectionAttempts}`); } render() { return (

Data: {this.state.data ? JSON.stringify(this.state.data) : 'Waiting...'}

Reconnection attempts: {this.state.connectionAttempts}

); } } export default RealTimeData; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.