Reputation:
My react app is supposed to render various widgets using the value in the search bar. In theory, I search something, and the widgets display the data using a script corresponding to the search value. Currently, when I search something, the widgets do not re-render with the data corresponding to the new searched value.
Here is the code for a widget:
import React, { Component } from 'react';
class SSIWidget extends React.Component {
constructor(props){
super(props);
}
componentDidMount() {
const script = document.createElement('script');
script.src ="https://s3.tradingview.com/external-embedding/embed-widget-symbol-info.js";
script.async = true;
script.innerHTML = JSON.stringify(
{
"symbol": props.value,
"width": 1000,
"locale": "en",
"colorTheme": "light",
"isTransparent": false
}
)
document.getElementById("myContainer6").appendChild(script);
}
render() {
return(
<div id="myContainer6">
<div className="tradingview-widget-container">
<div className="tradingview-widget-container__widget">
</div>
</div>
</div>
);
}
}
export default SSIWidget;
I tried to fix my issue with the following resources:
How to pass data from one component to another component in onchange using React js
Reactjs - passing state value from one component to another
I am passing an initialized search value for the widgets, which shows the data fine so I know I am passing the state correctly, but when I search a new value, it still shows the initial value data and not the new value data, bringing me to my hypothesis: the issue is probably because the script with the search value is only called when the component mounts, and not every time it renders.
How can I add the script in componentDidMount() to render() so that the widget re-renders every time the prop value changes?
Upvotes: 2
Views: 463
Reputation: 1270
You should use componentDidUpdate
here, move your logic to a separate function, call it in componentDidMount
and call it in componentDidUpdate
when prevProps.value !== this.props.value
From react docs:
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render. Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
componentDidMount() {
this.addWidget();
}
componentDidUpdate(prevProps, prevState) {
if(prevProps.value !== this.props.value) {
this.addWidget();
}
}
addWidget = () => {
// add widget logic
}
Upvotes: 1