Multiple components within a file - javascript

Says I have component A
like
export default class ComponentA extends components {
render(){
return() //use componentB here?
}
}
class ComponentB extends components {
}
how can I create another component and use it within ComponentA?

How can I create another component and use it within ComponentA?
There are two possible ways of doing that:
1- Define the component in the same file, exporting of that component will be not required because you will use that component in the same file.
2- Define the component in another file then export that component. Importing of component will be required in this case.
We can create as many components as we want in the same file, and we can use those components in the same way as we use HTML tags div, span, p etc.
Example:
Using ComponentB inside another component ComponentA:
export default class ComponentA extends components {
render(){
return(
<div>
{/*other code*/}
<ComponentB /> // notice here, rendering ComponentB
</div>
)
}
}
Define ComponentB in same file like this:
class ComponentB extends components {
}
Define ComponentB like this in another file:
export default class ComponentB extends components {
}

Just use it, like any other component:
export default class ComponentA extends components {
render() {
return <ComponentB />; // Use ComponentB here
}
}
class ComponentB extends components {
render() {
return <div>I'm B</div>;
}
}
Example:
/*export default*/ class ComponentA /*extends components*/ extends React.Component {
render() {
return <ComponentB />; // Use ComponentB here
}
}
class ComponentB /*extends components*/ extends React.Component {
render() {
return <div>I'm B</div>;
}
}
ReactDOM.render(
<ComponentA />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Yes, you are in the right track.
export default class ComponentA extends React.Component {
render(){
return(<ComponentB />);
}
}
class ComponentB extends React.Component {
render() {
return (<h1>Hello world! This is Component B</h1>)
}
}
or better yet, use stateless components like so: (if it's a really dumb component)
const ComponentB = () => (<h1>Hello world! This is Component B</h1>);

Related

How to properly create and render functional components?

I am attempting to create and render a functional component using the instructions here as a base. From what I've sen in there I should be able to do something along the lines of:
class MyComponent extends React.Component {
render() {
return (
<div>
<OtherComponent props="test" />
</div>
)}
function OtherComponent(props) {
return (
<div>
test
</div>
);
}
}
But this throws the error:
Unexpected token: function OtherComponent(props) {
^
I found a few posts that suggested removing the function so I tried that but then it throws the error:
OtherComponent is not defined
I'm able to get it working by creating a separate class component like so:
class OtherComponent extends React.Component {
render() {
But that's not what I want to do. What is the proper way to create/render a functional component in React.js?
For example this one works. See the docs ;)
React - Composing Components
function OtherComponent(props) {
return <div>test</div>;
}
class App extends React.Component {
render() {
return (
<div>
<OtherComponent props="test" />
</div>
);
}
}
Try this
class MyComponent extends React.Component {
OtherComponent = (props) => {
return (
<div>
test
</div>
);
}
render() {
return (
<div>
{this.OtherComponent("test")}
</div>
)}
}
You can't define a component inside of another component. A functional component means that the component is created from a function and is not a class. It can't have it's own state, because the state is initialized in class constructor. Check out this article for more info https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc
const otherComponent = (props) =>
<div>
test
</div>;
Here is another way. Its not correct to declare a component in a render function. If it is used solely in a parent component why not make that explicit and use static
class MyComponent extends React.Component {
static myOtherComponent = (props) => <div>{'test'}</div>
render(){
return(
<div>
<MyComponent.myOtherComponent {props} />
</div>
)
}
The myOtherComponent behaviour is controlled purely through the props it gets , it won't have its own state.
Or you could just make it a separate component e.g
export default myOtherComponent = (props) => ()
and import it into MyComponent. Please note , now with hooks ( see React Docs ), you can use hooks to mimic state etc in functional components and the latter approach might be your cleanest and most flexible approach.
This way you can define a function component
function OtherComponent(props) {
return <div>{props}</div>;
}
And now you can use functional component in your App (class component) like below
class App extends React.Component {
render() {
return (
<div>
<OtherComponent props="test" />
</div>
);
}
}

React.js passing data from class component to another in ReactDOM.render

I have this problem where I want to update my component FooBar if Foo's state changes. How can I do it? This doesn't work.
import React from "react"
import ReactDOM from "react-dom"
import FooBar from "./FooBar"
class Foo extends React.Component {
constructor() {
super()
this.state = { data: [] }
}
changeData() {
someCode
}
render() {
return (
some html
)
}
}
ReactDom.render(<Foo />, document.getElementById('Something'))
ReactDom.render(<FooBar data={this.state.data}/>, document.getElementById('SomethingElse'))
Question is a bit confusing, You can try this if it works
changeData = () =>
this.setState({data:'your changes'})
}
the above code will update the state, thus rest of component connected with class will render automatic.
Create a parent component, render both foo and foobar inside. now you can use state normally for communication between them and only have to use one ReactDom.Render
class Parent extends React.Component{
render(){
return(
<div>
<Foo/>
<Foobar/>
</div>
);
}
}
ReactDom.render(<Parent />, document.getElementById('Something'))

Relation between components

I have two stateful components:Grid and Item.Item is rendering by Grid and have props which reference to method (handler) defined in Grid <Item example={this.props.inGridHandler} />
Ok. But what if I have third stateful component let's name it Handy and I want that inGridHandler is defined not in Grid component as before but in Handy. How to achieve this with preserving all this structure ?
class Grid extends Component{
ingridHandler=()=>{
console.log('I want to be defined in Handy Component, not here');
}
Render(){
Return(
`<Item example={this.inGridHandler} />`
);
}
};
export default Grid;
class Handy extends Component{
inGridHandlerWantToBeDefinedHere=()=>{
console.log("I want to be defined here and pass to Grid component as props of Item component which is rendered there'
}
render(){
return(
)
}
}
Here is what you want if I understand you right. This is a very simple process. You are just passing the props all the way down. But, as I try to explain in my comments in the future you should think better approaches if you don't want to pass the props like this.
class Handy extends React.Component {
inGridHandler = () => {
console.log("ingridhandler");
};
render() {
return <Grid inGridHandler={this.inGridHandler} />;
}
}
class Grid extends React.Component {
render() {
return <Item inGridHandler={this.props.inGridHandler} />;
}
}
const Item = props => (
<button onClick={props.inGridHandler}>Click me and look the console.</button>
);
ReactDOM.render(
<Handy />,
document.getElementById("root")
);
<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>
<div id="root"></div>

React.JS Call childs component method from Parent Wrapper Component

I am working on React application and making something like a framework where I have a wrapper component some thing like this.
class FrameworkComponent extends React.Component {
someFunction() {
// send data to child data using childs function
// something like this.some.thing.childFunction("mydata");
...
}
render() {
return (
<div>
<div><button onClick={this.someFunction}>Click me</button></div>
<div>{this.props.child}</div>
</div>
)
}
}
and using it like this :
class SecondComponent extends React.Component {
childFunction(dataRecived) {
alert(dataRecived);
}
render() {
return <div>Hello world</div>;
}
}
import FrameworkComponent from '../FrameworkComponent';
import SecondComponent from '../SecondComponent';
class OtherComponet extends React.Component {
render() {
return (
<div>
<FrameworkComponent>
<div><SecondComponent /></div>
</FrameworkComponent>
</div>
)
}
}
So here I want child's component receive data from parent wrapper component either by updating its child props : componentWillReceiveProps() or calling its child method.
Your best bet would be to use HOC - Higher - https://reactjs.org/docs/higher-order-components.html

Load React using by on click of a button

I wants to create a class which while load a react.js file into a div specified using the react i had not found any thing related to that on net.
Check this example:
Lets say you have 2 component App and Child, and wants to render child component on checking the checkbox, this is called conditional rendering.
app.js file, import file child.js in App component:
import Child from './child';
class App extends React.Component {
constructor() {
super();
this.showComments = this.showComments.bind(this);
this.state = {
showComponent: false,
};
}
showComments(e) {
this.setState({
showComponent: e.target.checked,
});
}
render() {
return (
<div className="add_checkbox">
<span>Enable Comments</span>
<input className="checkbox" type="checkbox" name="enable_comment" onClick={this.showComments} value="enable_comment"/>
{this.state.showComponent ? <Child/> : null}
</div>
)
}
}
child.js file:
export default class Child extends React.Component{
render(){
return(
<div>Hello</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('container'));
Check fiddle for working example: https://jsfiddle.net/ztx9kd1w/
Let me know if you need any help.

Categories

Resources