import React, { useState } from "react";
export default function DropDown() {
const fun=()=>{
document.getElementById('id').innerHTML='Hello world'
}
return (
<>
<button onClick={fun()}>click</button>
<p id="id"></p>
</>
);
}
how to resolve the error in react? not in JavaScript. If we are not use inner HTML instead of that what to use in that field?
CodePudding user response:
Your immediate problem is that you are calling fun
immediately and then assigning its return value (undefined
) to onClick
.
To go about this the way you are trying, you need to assign the function itself.
onClick={fun}
However, direct DOM manipulation runs counter to the way React is designed to work.
Your changes are likely to get wiped out if anything triggers a re-render.
React is designed to be data driven. To change the DOM you should change the data and let React pull it through to the DOM itself.
You should make use of state to track the data.
export default function DropDown() {
const [open, setOpen] = useState(false);
const fun = useCallback(() => setOpen(open => !open), []);
return (
<>
<button onClick={fun}>click</button>
{open && (<p>Hello, world</p>)
</>
);
}
CodePudding user response:
In React, using the State Hook
https://reactjs.org/docs/hooks-state.html
Your code should be
import React, { useState } from "react";
export default function DropDown() {
const [greeting, setGreeting] = useState('Hello world');
const onChange = () => {
setGreeting('New greeting')
}
return (
<>
<button onClick={onChange}>click</button>
<p id="id">{greeting}</p>
</>
);
}
CodePudding user response:
This is because you are calling the fun
function instead of binding it to the click.
It should be : <button onClick={fun}>click</button>
See this CodeSandbox
CodePudding user response:
import React, { useState } from "react";
export default function DropDown() {
const [text,setText] useState('');
const fun=()=>{
setText('Hello world')
}
return (
<>
<button onClick={fun}>click</button>
<p id="id">{text}</p>
</>
);
}
Use state. Using innerHTML is not recommended. https://reactjs.org/docs/dom-elements.html
CodePudding user response:
That is not how you would do something like that in React.
In most cases, if you are working in React and find yourself manipulating the DOM (document.getElementById('id').innerHTML
) chances are you are doing it in the "wrong" way and you should double-check your work.
In this case, you should have something like:
import React, { useState } from 'react'
export default function DropDown() {
const [content, setContent] = useState();
const fun = () => {
setContent('Hello World!')
}
return (
<>
<button onClick={fun}>click</button>
<p>{content}</p>
</>
);
}