Reputation: 3226
I started adding React components to an existing website. I currently have a simple component that looks like this.
'use strict';
const element = React.createElement
class CourseForm extends React.Component {
constructor(props) {
super(props)
this.state = {
someObject: ''
}
}
changeObject() {
//this value will change on various events
this.setState({ someObject: {key: value} })
}
render() {
return (
<div>
This is a react form!
</div>
)
}
}
const domContainer = document.querySelector('#react-course-form')
ReactDOM.render(element(CourseForm), domContainer)
An html element is used to show the component.
<div id="react-course-form"></div>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<!-- Load React component. -->
<script type="text/babel" src="./js/components/CourseTabs.jsx"></script>
<script type="text/babel" src="./js/components/CourseForm.jsx"></script>
What I would like to do is include another componen, and send it data on events from this component.
render() {
return (
<div>
This is a react form!
<button onClick={this.changeObject}>change</button>
<div id="another-component" sendObject="this.state.someObject">
<div id="another-component2" sendObject="this.state.someObject">
</div>
)
}
So I basically want the child components to be aware of what someObject
is because they will be displaying data from that object.
Upvotes: 0
Views: 103
Reputation: 902
You can create another component and import in in your CourseForm component. Then you can just use it in your render method and send it the props as you do now in your example. You're using regular divs no though so it won't work.
example:
<AnotherComponent sendObject={this.state.someObject} />
When the state updates in your CourseForm component the child components will rerender automatically with the new data to it as props.
First create your new component:
class AnotherComponent extends Component {
// Your code goes in here. You can access the object data you send
// in by props by grabbing it from this.props.someObject
}
Then import it as a component in your CourseForm component:
import AnotherComponent from '.. your filepath here';
And use AnotherComponent in your render method in CourseForm:
<AnotherComponent sendObject={this.state.someObject} />
Upvotes: 1