I'm trying to get values from a form component using props into the main App component where my state is. Using the values i get from the props, i want to update the main state. This is my code:
class App extends Component { state = { dataset: "", cc: "", cw: 0, ch: 0, bw: 0, bh: 0, xspacing: 0, yspacing: 0, barcolor: "", };
// Function to use the data got from form component and setState
dataForm = (
dataset,
canvascolor,
canvaswidth,
canvasheight,
barwidth,
barheight,
xspacing,
yspacing,
barcolor
) => {
this.setState({
dataset,
canvascolor,
canvaswidth,
canvasheight,
barwidth,
barheight,
xspacing,
yspacing,
barcolor,
});
console.log(this.state);
};
render() {
return (
<div className="App">
{/* This is the Form Component from where i'm getting my Data */}
<DataForm dataForm={this.dataForm} />
<DataGraph graph={this.state} />
</div>
);
}
}
I am trying to send my updated state to the DataGraph component using props but it doesn't work, This is my DataGraph component code below:
class DataGraph extends Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
drawChart() {
const d = this.props.graph.dataset.split`,`.map((x) => +x);
const accessToRef = d3
.select(this.myRef.current)
.append("svg")
.attr("width", this.props.graph.cw)
.attr("height", this.props.graph.ch)
.style("background-color", this.props.graph.cc);
accessToRef
.selectAll("rect")
.data(d)
.enter()
.append("rect")
.attr("x", (d, i) => i * this.props.graph.xspacing)
.attr("y", (d, i) => this.props.graph.ch - this.props.graph.yspacing * d)
.attr("width", this.props.graph.bw)
.attr("height", (d, i) => d * this.props.graph.bh)
.attr("fill", this.props.graph.barcolor);
}
componentDidMount() {
this.drawChart();
}
render() {
return (
<>
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
ref={this.myRef}
className="pb-5"
></div>
</>
);
}
}
DataGraph.propTypes = {
graph: PropTypes.object.isRequired,
};
The setState() does not set the state values. Please help.
dataFormfunction is called at all, since this is where you are callingsetStatein. Then i would read up on the documentation ofDataForm(I assume that's not one of your own components) to see how it should be used and what data it passed to callbacks. Also note that some of the properties you pass tosetStatedon't exist in your component's state. Not sure whether that's relevant or not since we also don't know whatDataTableis or does.react-redux