Hot to call this function from another component in react?
function uCyr() {
var entered_text;
entered_text = document.getElementById('textarea').value;
entered_text = entered_text.replace(/a/g, 'b');
document.getElementById('textarea').style.color = '#9C27B0';
document.getElementById('textarea').value = entered_text;
}
Top comments (9)
My reply is based off on your Sandbox: codesandbox.io/s/strange-dust-98uwd
You can follow along w/ my fork: codesandbox.io/s/objective-mcnulty...
Here are a few things worth mentioning.
First issue
You are exporting
uCyr
as a default module.That means, you need to either alias it as
uCyr
in the calling code, or not use{}
during import.2nd issue
To bind an event handler, you shouldn't pass a string to
onClick
but actual function expression.Recommendation
Instead of getting the textarea using
document.getElementById("textarea")
, you should store thetextarea
value as a React state. Or you can useref
(but discouraged).It seems like you are used to the jQuery's unobstrusive coding style, but React requires a different mindset.
All changes should be state driven.
If you are unfamiliar with React states, I'd recommend React documentation.
reactjs.org/docs/state-and-lifecyc... or other materials of your choice because it's a very basic React knowledge required.
Thank you very much. You've helped me a lot
You're welcome & have fun with React~
Are you calling this from a functional component or a class component? Where and when do you want to call the component (on mount, after a specific condition, etc.)?
A very generic example of calling a function from JSX
A very generic example of calling a function before the return
A very generic example of calling a function in useEffect (from react docs)
Helpful links and further reading
reactjs.org/docs/faq-functions.html
reactjs.org/docs/hooks-effect.html
Call from here import React from "react";
import "./styles.css";
import './Ucyr';
import { Ucyr } from './Ucyr';
export default function App() {
return (
);
}
It's a good thing to bind first this function in your constructor, so you won't have a scope problem.
Then you can create a ref in the "another component" and apply it to this component where you have this function. Then you can call this.yourRef.current.uCyr()
codesandbox.io/s/strange-dust-98uwd
Where are the components?
codesandbox.io/s/strange-dust-98uwd