Can't access refs to call a method from a different component - javascript

I'm new to React-Native and I've been trying to call a method from another component, but I can't seem to access refs properly. Here's how my render method looks like
<Content contentContainerStyle={styles.content}>
...
<PostComponent style={styles.cardStyle} ref="cardRef" />
<View style={styles.horizontalTextContainer}>
<this.refs.cardRef.getText />
</View>
...
</Content>
In the PostComponent component, here's the method that I'm trying to call:
getText() {
return (
<Text>Hello</Text>
);
}
In the same component's constructor, I can use refs just fine to call a method like so:
constructor(props) {
super(props);
newthis = this
this.state = {
time: 20,
cards: [],
}
var timer = setInterval(() => {
this.setState({
time: --this.state.time,
})
if(this.state.time == 0) {
this.setState({
time: 20,
})
this.refs.cardRef.timesUp();
}
}, 1000);
}
Strangely, the ref works inside the setInverval method but not right outside it - how is the scope even working here? Also, if you notice I have a hacky "newthis" to save the global this - because in some methods of the component I can't access "this" (it's undefined).

In the constructor, when the call is made the component is still not mounted. refs can be safely accessed only after componentDidMount lifecycle method. Also string type refs are deprecated https://facebook.github.io/react/docs/refs-and-the-dom.html . Please use callback function syntax.
In your case, the refs are probably working in setInterval due to the time interval. The component would have mounted by 1000ms.
And to avoid hacky newThis, you can use arrow functions or bind this in the constructor. Most callback functions of the components have their own this context.
constructor(props) {
super(props);
newthis = this
this.state = {
time: 20,
cards: [],
}
}
componentDidMount() {
this.timer = setInterval(() => {
this.setState({
time: --this.state.time,
})
if(this.state.time == 0) {
this.setState({
time: 20,
})
this.cardRef.timesUp();
}
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timer)
}
...
<Content contentContainerStyle={styles.content}>
...
<PostComponent style={styles.cardStyle} ref={(ref) => this.cardRef = ref} />
<View style={styles.horizontalTextContainer}>
{this.cardRef.getText()}
</View>
...
</Content>

Related

React - how to pass a prop into a class function call that is then accessed in componentDidMount function

I'm new to coding and have spent a long time trying to make this work but I am stuck. I know this is a very basic question and if it is answered elsewhere, I have failed to find the right questions to search to find that answer.
This is from the react tutorial -- it is the automatic timer that self-updates every 1000ms. I would like to be able to pass a prop into the <Clock /> function call to specify the interval I want that specific object instance to use like so: <Clock interval=2000 />
Here is the code they provided:
function FormattedDate(props) {
return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<FormattedDate date={this.state.date} />
</div>
);
}
}
function App() {
return (
<div>
<Clock />
<Clock />
<Clock />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
Here is what I have tried:
Setting the state to have timer: 5000
passing it in as a const to the function call
then updating the state in componentDidMount
However, this does not work because I am trying to use a prop to update state. What am I supposed to do instead?
Unsuccessful code: (just the bits I've tried)
this.state = {
date: new Date(),
interval: 5000,
};
componentDidMount(props){
() => this.tick(),
props.timer
);
}
const timer = {
interval: 5000,
}
ReactDOM.render()
<Clock interval={timer.interval}/>,
document.getElementById('root')
);
if you want to pass the interval as a prop you can do it like this:
<Clock interval="1000"/>
and access it like this:
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
this.props.interval
);
}
You have to use this.props to have access to your props in the class components.

How to restart timer at the onPress in react native

I have made a small functionality for timer, where a timer will countdown from 10. When it reaches 0, the timer will hide, and a restart button will come at that place. Till this far, I am able to do it.
But I wanted to restart the timer when Restart appears after countdown is completed.
Below is the code:
constructor(props) {
super(props);
this.state = {
timer: 10,
displayButton: 'none',
displayTime: 'flex'
};
}
componentDidMount() {
this.clockCall = setInterval(() => {
this.decrementClock();
}, 1000);
}
decrementClock = () => {
this.setState(
(prevState) => ({timer: prevState.timer - 1}),
() => {
if (this.state.timer === 0) {
this.setState({
displayTime: "none",
displayButton: "flex"
})
}
},
);
};
restartButton() {
this.setState({
displayTime: "flex",
displayButton: "none",
timer: 30,
})
}
<Text style={{display: this.state.displayTime}}>{this.state.timer}</Text>
<TouchableOpacity onPress={this.restartButton}>
<Text style={{display:this.state.displayButton}}>Restart</Text>
</TouchableOpacity>
As you can see, Restart appears when countdown is finished, But when I click on Restart it is showing me error: Cannot read property 'setState' of undefined.
In the class component, we cannot directly call the methods that use this keyword as an in-class component this keyword refers to the object it called from as here it called from touchable opacity in might refers as the touchable object because of that you are receiving the error for this.setState is not a function as there is no function such as setState in touchable. so you have to bind the methods with a component to update the state or you can simply call the function as below code
onPress={() => this.restartButton()}
To bind the function you can use the below code in your class constructor
this.restartButton= this.restartButton.bind(this);
Bind your method
When you invoke the restartButton() function, it returns the value of this within the context which in this case is the null.
Since the this context of App is the one that restartButton() should be using, we have to use the .bind() method on it in the constructor.
constructor(props) {
super(props);
this.state = {
timer: 10,
displayButton: 'none',
displayTime: 'flex'
};
this.restartButton= this.restartButton.bind(this);
}
and the other approach(arrow-function) is if you don't want to bind the function
restartButton =()=> {
this.setState({
displayTime: "flex",
displayButton: "none",
timer: 30,
})
}

Conditional creation of an object

I am working with Chartjs and trying to create the chart object once within a function. Then skipping that piece of code in the function so it will just update the chart on future calls.
I am not not sure how to structure the conditional chart object creation. Below is my code approach ( it does not run atm).
class BtcOverview extends React.Component {
constructor(props) {
super(props);
this.canvasRef = React.createRef();
}
componentDidMount () {
this.callApi();
}
callApi = () => {
fetch(getApi())
.then(results => results.json())
.then(marketData => {
//API FETCH STUFF
const chartOptions = {
...{}
...this.props.chartOptions
};
const BtcChart = new Chart(this.canvasRef.current, {
type: "LineWithLine",
data: this.props.chartData,
options: chartOptions
});
BtcChart.render();
// I want to create the BtcChart and render() on the first run. But then after that only call update() on the chart object
})
}
render() {
return (
<>
<CardBody className="pt-2">
<canvas
height="160"
ref={this.canvasRef}
style={{ maxWidth: "100% !important" }} className="mb-1" />
</CardBody>
</Card>
</>
);
}
}
Update: I should explain a bit more clearly. I want to be be able to create a 'new Chart' once and then on subsequent runs rather call BtcChart update given the chart object already exists.
When I tried to use an if-else statement to achieve that it would not compile because I guess because the chart BtcChart has not been created at the time of compiling and possibly a scope issue. So I am have been trying hacks that are probably wrong in their approach.

Trouble Getting Component to Render in setTimeout

Not sure what I'm doing wrong but my component wrapped in setTimeout is not being rendered to the DOM:
const ContentMain = Component({
getInitialState() {
return {rendered: false};
},
componentDidMount() {
this.setState({rendered: true});
},
render(){
var company = this.props.company;
return (
<div id="ft-content">
{this.state.rendered && setTimeout(() => <Content company={company}/>,3000)}
</div>
)
}
})
I'd bet this isn't working because the render method needs all of its input to be consumed at the same time and it can't render other components in retrospect, there's a certain flow to React. I'd suggest to separate the timeout from render method anyway for logic's sake, and do it in componentDidMount like this:
const ContentMain = Component({
getInitialState() {
return {rendered: false};
},
componentDidMount() {
setTimeout(() => {
this.setState({rendered: true});
}, 3000);
},
render(){
if (!this.state.rendered) {
return null;
}
var company = this.props.company;
return (
<div id="ft-content">
<Content company={company}/>
</div>
)
}
})
Changing the state triggers the render method.
On a side note - even if your original approach worked, you'd see the component flicker for 3 seconds every time it got rendered after the initial load. Guessing you wouldn't want that :)

setState() inside of componentDidUpdate()

I'm writing a script which moves dropdown below or above input depending on height of dropdown and position of the input on the screen. Also I want to set modifier to dropdown according to its direction.
But using setState inside of the componentDidUpdate creates an infinite loop(which is obvious)
I've found a solution in using getDOMNode and setting classname to dropdown directly, but i feel that there should be a better solution using React tools. Can anybody help me?
Here is a part of working code with getDOMNode (i
a little bit neglected positioning logic to simplify code)
let SearchDropdown = React.createClass({
componentDidUpdate(params) {
let el = this.getDOMNode();
el.classList.remove('dropDown-top');
if(needToMoveOnTop(el)) {
el.top = newTopValue;
el.right = newRightValue;
el.classList.add('dropDown-top');
}
},
render() {
let dataFeed = this.props.dataFeed;
return (
<DropDown >
{dataFeed.map((data, i) => {
return (<DropDownRow key={response.symbol} data={data}/>);
})}
</DropDown>
);
}
});
and here is code with setstate (which creates an infinite loop)
let SearchDropdown = React.createClass({
getInitialState() {
return {
top: false
};
},
componentDidUpdate(params) {
let el = this.getDOMNode();
if (this.state.top) {
this.setState({top: false});
}
if(needToMoveOnTop(el)) {
el.top = newTopValue;
el.right = newRightValue;
if (!this.state.top) {
this.setState({top: true});
}
}
},
render() {
let dataFeed = this.props.dataFeed;
let class = cx({'dropDown-top' : this.state.top});
return (
<DropDown className={class} >
{dataFeed.map((data, i) => {
return (<DropDownRow key={response.symbol} data={data}/>);
})}
</DropDown>
);
}
});
You can use setStateinside componentDidUpdate. The problem is that somehow you are creating an infinite loop because there's no break condition.
Based on the fact that you need values that are provided by the browser once the component is rendered, I think your approach about using componentDidUpdate is correct, it just needs better handling of the condition that triggers the setState.
The componentDidUpdate signature is void::componentDidUpdate(previousProps, previousState). With this you will be able to test which props/state are dirty and call setState accordingly.
Example:
componentDidUpdate(previousProps, previousState) {
if (previousProps.data !== this.props.data) {
this.setState({/*....*/})
}
}
If you use setState inside componentDidUpdate it updates the component, resulting in a call to componentDidUpdate which subsequently calls setState again resulting in the infinite loop. You should conditionally call setState and ensure that the condition violating the call occurs eventually e.g:
componentDidUpdate: function() {
if (condition) {
this.setState({..})
} else {
//do something else
}
}
In case you are only updating the component by sending props to it(it is not being updated by setState, except for the case inside componentDidUpdate), you can call setState inside componentWillReceiveProps instead of componentDidUpdate.
This example will help you to understand the React Life Cycle Hooks.
You can setState in getDerivedStateFromProps method i.e. static and trigger the method after props change in componentDidUpdate.
In componentDidUpdate you will get 3rd param which returns from getSnapshotBeforeUpdate.
You can check this codesandbox link
// Child component
class Child extends React.Component {
// First thing called when component loaded
constructor(props) {
console.log("constructor");
super(props);
this.state = {
value: this.props.value,
color: "green"
};
}
// static method
// dont have access of 'this'
// return object will update the state
static getDerivedStateFromProps(props, state) {
console.log("getDerivedStateFromProps");
return {
value: props.value,
color: props.value % 2 === 0 ? "green" : "red"
};
}
// skip render if return false
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate");
// return nextState.color !== this.state.color;
return true;
}
// In between before real DOM updates (pre-commit)
// has access of 'this'
// return object will be captured in componentDidUpdate
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log("getSnapshotBeforeUpdate");
return { oldValue: prevState.value };
}
// Calls after component updated
// has access of previous state and props with snapshot
// Can call methods here
// setState inside this will cause infinite loop
componentDidUpdate(prevProps, prevState, snapshot) {
console.log("componentDidUpdate: ", prevProps, prevState, snapshot);
}
static getDerivedStateFromError(error) {
console.log("getDerivedStateFromError");
return { hasError: true };
}
componentDidCatch(error, info) {
console.log("componentDidCatch: ", error, info);
}
// After component mount
// Good place to start AJAX call and initial state
componentDidMount() {
console.log("componentDidMount");
this.makeAjaxCall();
}
makeAjaxCall() {
console.log("makeAjaxCall");
}
onClick() {
console.log("state: ", this.state);
}
render() {
return (
<div style={{ border: "1px solid red", padding: "0px 10px 10px 10px" }}>
<p style={{ color: this.state.color }}>Color: {this.state.color}</p>
<button onClick={() => this.onClick()}>{this.props.value}</button>
</div>
);
}
}
// Parent component
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { value: 1 };
this.tick = () => {
this.setState({
date: new Date(),
value: this.state.value + 1
});
};
}
componentDidMount() {
setTimeout(this.tick, 2000);
}
render() {
return (
<div style={{ border: "1px solid blue", padding: "0px 10px 10px 10px" }}>
<p>Parent</p>
<Child value={this.state.value} />
</div>
);
}
}
function App() {
return (
<React.Fragment>
<Parent />
</React.Fragment>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I would say that you need to check if the state already has the same value you are trying to set. If it's the same, there is no point to set state again for the same value.
Make sure to set your state like this:
let top = newValue /*true or false*/
if(top !== this.state.top){
this.setState({top});
}
this.setState creates an infinite loop when used in ComponentDidUpdate when there is no break condition in the loop.
You can use redux to set a variable true in the if statement and then in the condition set the variable false then it will work.
Something like this.
if(this.props.route.params.resetFields){
this.props.route.params.resetFields = false;
this.setState({broadcastMembersCount: 0,isLinkAttached: false,attachedAffiliatedLink:false,affilatedText: 'add your affiliate link'});
this.resetSelectedContactAndGroups();
this.hideNext = false;
this.initialValue_1 = 140;
this.initialValue_2 = 140;
this.height = 20
}
I faced similar issue. Please make componentDidUpdate an arrow function. That should work.
componentDidUpdate = (params) => {
let el = this.getDOMNode();
if (this.state.top) {
this.setState({top: false});
}
if(needToMoveOnTop(el)) {
el.top = newTopValue;
el.right = newRightValue;
if (!this.state.top) {
this.setState({top: true});
}
}
}
I had a similar problem where i have to center the toolTip. React setState in componentDidUpdate did put me in infinite loop, i tried condition it worked. But i found using in ref callback gave me simpler and clean solution, if you use inline function for ref callback you will face the null problem for every component update. So use function reference in ref callback and set the state there, which will initiate the re-render
You can use setState inside componentDidUpdate

Categories