How to passing refs to component in React - reactjs

I have a data like this:
constructor(props) {
this.a = React.createRef();
this.b = React.createRef();
this.c = React.createRef();
}
setValue = (data = {}) => {
const {a='', b='', c=''} = data.constructor === ({}).constructor ? data : {};
this.a.current.setValue(a, data => {
this.b.current.setValue(data.b, data => {
this.c.current.setValue(data.c);
}
}
}
}
How could I passing that to my customized Component like this:
<CusComponent ref={this.a}>
Here is the function to get value in CusComponent:
value = function (a,b,c) {
if (arguments.length) {
if (a) {
this.setState({a}, () => {
this.value_a.value(a);
if (b) {
this.setState({b}, () => {
this.value_b.value(b);
if (c) {
this.setState({c}, () => {
this.value_c.value(c);
}
}
})
}
}
}
Thanks a lot!

Yes you can pass a ref down to a child component with:
<CusComponent ref={this.a}>
Make sure you create CusComponent with React.forwardRef because that creates an argument ref alongside props. This `ref you can directly bind to anything in your child component.
const CusComponent = React.forwardRef((props, ref) => (
<button ref={ref}>
{props.children}
</button>
));
You can read more in detail about this in the documentation.
If however both your parent and child component are class components then pass down the ref to CusComponent like so:
<CusComponent childref={this.a}>
Name the property something other than ref. Then you can access this ref in child component like below eg.
export default class CusComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div ref={this.props.childref}>Here</div>;
}
}

Related

Pass original component's function to react HOC

I have created react HOC component as below.
const UpdatedComponent = (OriginalComponent) => {
class NewComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
counter:0
}
}
componentDidMount(){
}
incrementCount = () => {
this.setState(prevState => {
return {counter:prevState.counter+1}
})
}
render(){
return <OriginalComponent
incrementCount={this.incrementCount}
count={this.state.counter}
/>
}
}
return NewComponent
}
export default UpdatedComponent
and I am using that component in the below example
class HoverCounter extends Component {
componentDidMount(){
}
handleMessages = () => {
// need to do somthing
}
render() {
const {incrementCount, count} = this.props
return (
<div onMouseOver={incrementCount}>
Hoverd {count} times
</div>
)
}
}
export default UpdatedComponent(HoverCounter)
I want to know that is it possible to pass
handleMessages()
function to HOC?
like this
export default UpdatedComponent(HoverCounter,handleMessages)
I have no idea how to pass the original component function or props to HOC.
you could get everyThing in your Hoc like this :
const UpdatedComponent = (OriginalComponent , func) => {
componentDidMount(){
func()
}
in HoverCounter also you could add this changes:
static handleMessages(){
// need to do something
}
export default UpdatedComponent(HoverCounter , HoverCounter.handleMessages)

Ref undefined in ReactJs

When I try to use slider ref inside functionB I'm getting ref undefined error.What am i doing wrong here?
class somecomp extends Component {
constructor(props){
super(props);
this.slider = React.createRef;
}
componentDidMount(){
this.functionA();
}
functionA = () => {
functionB();
}
functionB = () => {
// When i call slider ref here im getting ref undefined
}
render() {
return (
<div ref={slider => (this.slider = slider)}></div>
);
}
}
export default somecomp;
I assume the root of your problem here
this.slider = React.createRef
You are not create ref you pass function which creates ref to slider
Try to use it in such way
this.slider = React.createRef();
Also this
<div ref={slider => (this.slider = slider)}></div>
Might be simplified to this
<div ref={this.slider}></div>
Also do not forget to user current property of ref
In your situation it will be
const node = this.slider.current;
Few problems you've in your code that should be corrected https://codesandbox.io/s/determined-lamport-gfv9j
class somecomp extends Component {
constructor(props){
super(props);
this.slider = React.createRef; // use React.createRef() at here
}
componentDidMount(){
this.functionA();
}
functionA = () => {
functionB(); // use this.functionB() at here
}
functionB = () => {
console.log("this.slider", this.slider);
// When i call slider ref here im getting ref undefined
}
render() {
return (
<div ref={slider => (this.slider = slider)}></div>
);
}
}
export default somecomp;

Call a function of one of a list of children components of the parent component using reference

For my website I want to include a feature that helps users randomly click a link programatically. The event happens in the parent component called StreamingPlaza, and its has a list of children components called StreamingCard, each containing a streaming link. Below is my code:
StreamingPlaza
class StreamingPlaza extends Component {
state = {
......
}
roomclicks = [];
componentDidMount() {
//Approach 1//
this.roomclicks[0].current.handleClick();
//Approach 2//
this.roomclicks[0].props.click = true;
......
}
setRef = (ref) => {
this.roomclicks.push(ref);
}
renderRoom = (room) => {
return <StreamingCard info={room} ref={this.setRef} click={false}></StreamingCard>;
}
render () {
const rooms = this.props.rooms;
return (
{ rooms && rooms.map (room => {
return this.renderRoom(room);
})
}
);
}
StreamingCard
class StreamingCard extends Component {
constructor(props){
super(props);
this.state = {
......
}
}
handleClick = () => {
document.getElementById("link").click();
}
render() {
return (
✔️ Streaming Link: <a id="link" href=......></a>
);
}
Regarding Approach 1, the console reported the error Cannot read property handClick of undefined. After I removed "current", it said that this.roomclicks[0].handleClick is not a function. Regarding Approach 2, I was not able to modify the props in this way, as the console reported that "click" is read-only.
Approach 1 is basically how its need to be done, but with React API.
See React.createRef
class StreamingPlaza extends Component {
roomclicks = React.createRef([]);
componentDidMount() {
// 0 is room.id
this.roomclicks.current[0].handleClick();
}
renderRoom = (room) => {
return (
<StreamingCard
info={room}
ref={(ref) => (this.roomclicks.current[room.id] = ref)}
click={false}
></StreamingCard>
);
};
render() {
const rooms = this.props.rooms;
return rooms.map((room) => {
return this.renderRoom(room);
});
}
}

ReactJS: Trigger event from child in parent component

i have two components: 1.Parent 2.Child
there is an event in child component called onChange() which return a value.
i want to receive the value which was returned from OnChange() in componentDidMount() in parent component.
Example:
class Parent extends PureComponent {
componentDidMount() {
let value = CHILD.onChange(); //triggered when ever onChange()
}
render(){
return(
<Child />
)
}
}
const Child = () => {
const onChange = () => {
const value = 1
return value;
};
}
class Parent extends PureComponent {
handleChildChange = value => {
//Do your stuff with value, pass it to the state and take it from there if you like
}
render(){
return(
<Child handleChange={this.handleChildChange} />
)
}
}
const Child = (props) => {
const onChange = () => {
value = 1
props.handleChange(value);
}
};
}

React Native Pass Parent Method to Child Component

I am trying to pass method from my parent component to child component. My code is correct i think but still it shows the error undefined is not an object(evaluating '_this2.props.updateData') . I don't know whats the issue because i searched the internet a lot and everyone is passing props to child like this. Kindly tell what am i missing
Parent:
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
// data should be 'child data' when the
// Test button in the child component is clicked
}
render() {
return (
<Child updateData={val => this.updateData(val)} />
);
}
Child:
class Child extends React.Component {
const passedData = 'child data'
handleClick = () => {
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick()}>Test</button>
);
}
}
`class Child extends React.Component {
handleClick = () => {
const passedData = 'child data'
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick}>Test</button>
);
}
}`
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
}
render() {
return (
<Child updateData={this.updateData} />
);
}
}
and child component: `
class Child extends React.Component {
const passedData = 'child data'
handleClick = () => {
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick}>Test</button>
);
}
}
`
You need to pass the function directly, not as a callback
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
// data should be 'child data' when the
// Test button in the child component is clicked
}
render() {
return (
<Child updateData={this.updateData} />
);
}
I think you need to pass a function like this. Check out this solution.

Resources