Dales Vu
Dales Vu

Reputation: 169

Convert class component to functional components using hooks

I am trying to convert this class component to functional component using hooks

import React, { Component, cloneElement } from 'react';

class Dialog extends Component {
    constructor(props) {
        super(props);
        this.id = uuid();       
   }
   render(){
     return ( <div>Hello Dialog</div> );
  }
}

This component is initiated with a specific ID because I may have to use multiple instances of them. How can I achieve this if I use functional component?

Upvotes: 1

Views: 236

Answers (4)

Dales Vu
Dales Vu

Reputation: 169

Thank you all, your solutions works well. I also try this solution and I find it OK too: replace this.id with Dialog.id. Is there any downside with this solution?

Upvotes: 1

hangindev.com
hangindev.com

Reputation: 4873

You may store it in state:

const [id] = useState(uuid()); // uuid will be called in every render but only the first one will be used for initiation 

// or using lazy initial state
const [id] = useState(() => uuid()); // uuid will only be called once for initiation 

You may also store it in React ref:

const id = useRef(null);
if(!id.current) {
    // initialise 
    id.current = uuid();
}
// To access it’s value
console.log(id.current);

Upvotes: 3

Momin
Momin

Reputation: 3320

Any instance property becomes a ref pretty much, and you would access idRef.current in this case for the id

function Dialog() {
  const idRef = useRef(uuid())
  return <div>Hello Dialog</div>
}

Upvotes: 1

Treycos
Treycos

Reputation: 7492

One solution would be to use useEffect to create your ID at the first render, and store it in the state :

const Dialog = () => {
    const [id, setId] = useState(null);

    useEffect(() => {
        setId(uuid())
    }, [])

    return <div>Hello Dialog</div>
}

Giving an empty array as the second parameter of useEffect makes it unable to trigger more than once.

But another extremely simple solution could be to just... create it outside of your component :

const id = uuid();

const Dialog = () => {
    return <div>Hello Dialog</div>
}

Upvotes: 4

Related Questions