skip to Main Content

I would like to convert React class component to functional component.

const remoteVideoref = useRef(null);

this.pc.ontrack = (e) => {
      this.remoteVideoref.current.srcObject = e.streams[0]
    }

Is this the correct way of doing it?

const remoteVideoref = useRef(null);

this.pc.ontrack = (e) => {
      remoteVideoref.current.srcObject = e.streams[0]
    }

2

Answers


  1. Assume this class component:

    import React, { Component } from 'react';
    
    class App extends Component {
      state = {
        name: ''
      }
    
      alertName = () => {
        alert(this.state.name);
      };
    
      handleNameInput = e => {
        this.setState({ name: e.target.value });
      };
    
      render() {
        return (
          <div>
            <h3>This is a Class Component</h3>
            <input
              type="text"
              onChange={this.handleNameInput}
              value={this.state.name}
              placeholder="Your Name"
            />
            <button onClick={this.alertName}>
              Alert
            </button>
          </div>
        );
      }
    }
    
    export default App;
    

    When you types a name in the input field and clicks the Alert button, it pops up an alert with the name defined in state.

    You can convert this entire class into a functional React component using Hooks:

    import React, { useState } from 'react';
        
        function App() {
          const [name, setName] = useState('John Doe');
        
          const alertName = () => {
            alert(name);
          };
        
          const handleNameInput = e => {
            setName(e.target.value);
          };
        
          return (
            <div>
              <h3>This is a Functional Component</h3>
              <input
                type="text"
                onChange={handleNameInput}
                value={name}
                placeholder="Your Name"
              />
              <button onClick={alertName}>
                Alert
              </button>
            </div>
          );
        };
        
        export default App;
    

    If this is what you mean, then I hope this helps.

    Login or Signup to reply.
  2. function component code for your code will be as following

    const remoteVideoref = useRef(null);
    
    const ontrack = (e) => {
      remoteVideoref.current.srcObject = e.streams[0]
    }
    

    and your can call ontrack function anywhere like ontrack(event)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search