2

Is it possible to append buttons with event handler in react ?

// This is working fine but its pure javascript onclick , how can I make this element with react js onClick ?

This is reference code , my scenario is appending html code dynamically

const Button = () => {
      const dynamicElement = () => {
           let li = document.createElement('li');
               li.className = 'dynamic-link'; // Class name
               li.innerHTML = "I am New"; // Text inside
               document.getElementById('links').appendChild(li);
               li.onclick = function(){ alert(0) } 
      }

         useEffect(() => {
             dynamicElement();
         }, [])
}

1 Answer 1

5

You can just convert your function to a functional component like this.

const DynamicElement = () => {
    return (
      <li onClick={()=>alert(0)} className="dynamic-link">I am New</li>
    )
}
const Button = () => {
    const [visible, setVisible] = useState(false);
    useEffect(()=>setVisible(true), [])
    // if visible is true return <DynamicElement/>, either way return null
    return visible ? <DynamicElement/> : null
}

BTW useState is hooks implementation of a state

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.