How to redefine a Class Component method in React? - javascript

I want to redefine a function/method inside a Class Component because I want to reuse it.
I tried
ClassComponent.prototype.submitForm = async () => {
...
}
but no luck.
In Jest, it is possible to do
jest.spyOn(class.prototype, 'method').mockImplementation
to change the implementation of the method. But I want to do it in React. Is there a way to do this? I need to change that method so I can fully reuse my Component. Thanks

I don't have your code to have a better context, but from what I see - you're going in a wrong direction. If you wish to overwrite the behavior of an inner-function inside the component, just overwrite it when a certain condition applies. You can check this condition in an event/hook or on init.

Related

Vue3 call a components method from another component

I'm trying to have a component call a function from another component but just from
inside the setup.
I've read this from vuemastery https://www.vuemastery.com/blog/understanding-vue-3-expose/
and I see that you can accomplish this like this:
methods: {
reset () {
this.$refs.counter.reset()
},
terminate () {
this.$refs.counter.terminate()
}
}
however, I don't have access to those methods inside the setup, and I also can't use this.$refs inside the setup. Is there a way I can do the same thing inside setup, or a way to access these methods inside the setup?
Those methods are undefined in setup, and I cannot access data setup from within those functions, and I cannot use $refs in setup.
The $refs is a very easy way to call a function from another component - but I can't seem to find a relatively easy way to do this with vue3 composition api - am I missing something?
Hey I figured it out https://vuejs.org/guide/essentials/template-refs.html#accessing-the-refs
If I go
<script>
export default {
setup(props) {
const counter = ref(null);
//now I have access to counter.value.reset after it's mounted
counter.value.reset(); //does not work! it's null here
onMounted(() => {
counter.value.reset(); //here it works
})
//make sure to return counter in return
looks like there is an easy way to do this in setup just has a caveat
you cant just call it right away because setup happens before mounted https://vuejs.org/guide/essentials/lifecycle.html
I am calling it on a trigger - so if someone selects something from a dropdown I am watching the v-model and am able to call it there no problem.
Thanks for all the input.
Putting this answer here in case anyone else needs to accomplish the same thing

ReactJS How to pass a prop to a component in state

function App() {
const [currentPanel, setCurrentPanel] = useState(ProfilePanel); // ProfilePanel is a component
return (
<div className={styles.App}>
{currentPanel}
</div>
);
}
In code i set the component "ProfilePanel" to a "curentPanlel" state, then in App i change the component in state, and this render an another panel. the problem is that i dont know how to pass props when i render it like this.
i tried the {currentPanel()} but is return an error.
please help to find a method to solve this, or if this method to render a component in state are absolutly wrong tell how to do this another way.
the problem is that i dont know how to pass props when i render it like this
You'd do it by using an initial capital letter for the state member (CurrentPanel instead of currentPanel), and then using it as normal (<CurrentPanel someProp="some value" />). (It has to be initially-capped because that's how JSX knows it's supposed to be a component, not a tag name.) But, you'll struggle to set a different component function in state, because component functions are, well, functions, and when you pass a function to a state setter, it thinks you're using the callback version of the state setter and calls your function, rather than setting it in state.
If you absolutely have to hold a component function in state, wrap it in an object, but it's much more likely that there's a better solution to the overall problem you're trying to solve.

What is the best way to get the name of a React component?

I have been struggling about finding a method to get the name of a React component. I tried the this.constructor.name property. However learnt that it doesn't work in production mode since Webpack minifies the code. Is there any way I can use without any caveats?
It's up on from where you need the name. If you can treat the component as a function (with hooks) you could just call Function.name
function MyComponent({giveNameToParent}){
const sendInfo(){
giveNameToParent(MyComponent.name);
}
return (
<div onClick={sendInfo}>Hi there!</div>
);
}
I don't know if this can solve your problem, but if you need something more solid, please give more context to your case.
Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

Is this a React bad practice?

So, I'm trying to learn some react, so far egghead.io is pretty good, but I have a question. I have the following code:
https://jsfiddle.net/42pe/69z2wepo/49393/
Basically these are 3 sliders which update the state on the parent component. Pretty straightforward.
Specifically, I can update the state like this (by passing both val and color):
updateMe(val, color) {
let obj = {};
obj[color] = val;
this.setState(obj);
}
Or I could use the Slider ref to findDOMNode() and then get the value to update the state, but that just didn't feel right. I have no clue what React does in the back, but calling a function from an instance, just so that function can find the instance again to get it's value, when the instance itself could be passing it's value (both value and color prop) all along seems weird.
So, is this a bad practice for some reason?
Both methods are correct but prefer the updateMe . Passing functions in props and child calling that prop function is the ideal way in React.
Refs are ideal where you just want the value and dont want to update state of the react component .For eg , in forms you can use ref to get all the values and make a ajax call to the server.
A better and much cleaner way to do this using ES6 is:
updateMe(val, color) {
this.setState({
[color]: val
});
}
findDOMNode is not a bad practice. But you do not need use it if, you build your application as a function of state and props.
Any change to your state or props should change your DOM and any change to your DOM should be as a result of function of change in state or props.

Best pattern to rerender my react component?

I have a global data object I update and then I call React.renderComponent() again on the top/main component.
Is this the right pattern for triggering this update?
You should generally pass the data object into the component as a prop, even if it's a global variable. This lets you test the component, and also use it elsewhere without being tied to that global.
As Mike said, there's nothing wrong with using React.renderComponent to update it.
He also mentioned flux, but that's overkill for this. A simple event emitter where you do something like .emit('change', newData), and the component is listening for the change event tends to be better for simpler cases. See my answer to this question for an example of how that can be done.
This is the correct pattern. React.renderComponent will either mount a component for the first time, or get an already mounted component to update.
If you're using a global object though, you might want to look in to the Flux architecture here:
http://facebook.github.io/flux/docs/overview.html
I had the same problem and asked myself if I really needed to re-render the component.
You can do so with this.forceUpdate() but it's not advisable. As React docs states:
You should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). This makes your component "pure" and your application much simpler and more efficient.
So what I did was create a data property like exists and test it:
// renderDeleteButton() is being called on render()
renderDeleteButton () {
if (!this.props.store.exists) {
return;
}
return(
<DeleteButton
...
deleteAction={this.delete} />
);
}
Whenever I delete/save, I toggle exists and component will show up or hide based on that. React handles that for me.

Categories

Resources