my page.js
class R1 extends React.Component {
render() {
return (
<div className="r1">
<h1>level1</h1>
</div>
);
}
}
class R2 extends React.Component {
render() {
return (
<div className="r2">
<h1>level2</h1>
</div>
);
}
}
my main.js
important * as Page from './page';
class App extends React.Component {
render() {
return (
<div className="r1">
<Page.R+level/>
</div>
);
}
}
Skip getInitialState,
I want to dynamic render with level.
I try React.renderComponent(<Page.R+this.state.level />, document.body);
It's not working with failed: SyntaxError
Is there more easily way? or is dynamic render available?
thanks
Not sure how you are exporting your Components so there is an assumption here, generally it is convention to put them in different files.
You can render in your parent component using an if statement inside JSX like this:
class App extends React.Component {
render() {
var renderPage;
if (something) {
renderPage = <PageOne />;
} else {
renderPage = <PageTwo />;
}
return (
<div>
{renderPage}
</div>
);
}
}
main.js can be modified like this to achieve what you want
import * as Page from './page';
class App extends React.Component {
render() {
const level = 2;
return (
<div className="r1">
{/*You use loop over list to get value of level and render all the pages*/}
{React.createElement(Page[`R${level}`], null)}
</div>
);
}
}
Page is an object and we are trying to access the pages and rendering the component name which is in string type.
Related
At the button click Create I want to display the room with the content (the new values that holds by the objects in the array - the value I wrote inside the inputs) but fro some reason it's not working and I can't solve it, the problem is that only the template that shows the titles Room and Type are shown without the values inside each of them
Thanks to the helpers!
App.js
import React, { Component } from 'react'
import './App.css';
import Addroom from './components/Addroom.js'
import Room from './components/Room.js'
import 'bootstrap/dist/css/bootstrap.css';
export default class App extends Component {
state={roomsList:[{room:'',type:''}]
}
create=(r,t)=> {
this.setState({roomsList:[...this.state.roomsList,{room:r,type:t}]})
}
render() {
return (
<div>
<h1>My Smart House</h1>
{this.state.roomsList.map((element)=>{
return <Room r={element.room} t={element.type} />
})}
<Addroom add={this.create}/>
</div>
)
}
}
Addroom.js
import React, { Component } from 'react'
export default class Addroom extends Component {
constructor(props) {
super(props)
}
addRoomName=(e)=> {
this.setState({room:e.target.value})
}
addType=(e)=> {
this.setState({type:e.target.value})
}
createRoom=()=> {
this.props.add(this.state.room,this.state.type);
}
render() {
return (
<div>
<input onChange={this.addRoomName} placeholder='Name Your Room'/><br/>
<input onChange={this.addType} placeholder='Whats The Room Type?'/><br/>
<button onClick={this.createRoom}>Create</button>
</div>
)
}
}
Room.js
import React, { Component } from 'react'
export default class Room extends Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return (
<div>
<h1>Room: {this.props.room} </h1>
<h3>Type: {this.props.type} </h3>
</div>
)
}
}
I solved the error, it was a syntax mistake, so what i did, I just asked to get the inside value from my objects in the Room.js components, So it looked like that before:
render() {
return (
<div>
<h1>Room: {this.props.room} </h1>
<h3>Color: {this.props.type} </h3>
</div>
)
}
}
and now I just fixed the syntax to make App.js component understand that I want to display the values inside the objects when I'm creating a new room with my button, because now r and t are represent the values of the variables..
render() {
return (
<div>
<h1>Room: {this.props.r} </h1>
<h3>Color: {this.props.t} </h3>
</div>
)
}
}
This is a very small mistake that is easy to understand, so it is always important to go through your code slowly and safely! Hope it will help some f.e devs in the future..
In my code I have to use the same lines of code at different places. So i thought that's the right time to put this code into a kind of base class. I've read about Higher-Order Components which seems to be the way to go and following some examples i ended up with the following code, which is not working. I've tried something around but was not able to get it work.
My HOC:
export interface HocProps {
DynamicId: string
}
const withDiv = (hocProps) => (BaseComponent) => {
return class extend React.Component {
render() {
return (
<div id={ hocProps.DynamicId }>
<BaseComponent />
</div>
);
}
}
}
export default withDiv;
A component to be wrapped by the div:
import withDiv from './MyHoc';
class MyComponent extends React.Component {
render() {
return (
<h3>Some content here</h3>
);
}
}
export default withDiv({ DynamicId: <dynamic value> })(MyComponent);
Another component, that uses MyComponent:
import MyComponent from './MyComponent';
export class OtherComponent extends React.Component {
render() {
return (
<div>
... Some content here ...
<MyComponent DynamicId={ 'id123' } />
</div>
);
}
}
I'd like to pass an id to in OtherComponent. Then in MyComponent this id has to be passed to the HOC as , which is not working. I only can pass static values to the HOC.
I'm new to react and I think i've made same mistake(s).
So my question is: What am i doing wrong and how is it done right?
Maybe there is another/better way for this?
Thanks in advance.
Edit:
I would expect this result:
<div>
... Some content here ...
<div id='id123'>
<h3>Some content here</h3>
</div>
</div>
There are two ways you can use HOCs according to your implementation.
I have created a sandbox, which will help you understand how to use HOCs.
One way is to extract your props out const hocWrapper = Component => props => { // return NewComponent and call it too }. Here you have to call your component while returning.
Other way is to destructure or use the props inside hocWrappers. const hocWrapper = Component => { // return NewComponent, you will receive props inside the newComponent and do what you wish}
Try this
const withDiv = (BaseComponent) => {
class CompWithDiv extends React.Component {
render() {
return (
<div id={this.props.DynamicId}>
<BaseComponent />
</div>
);
}
}
return CompWithDiv ;
}
export default withDiv;
Im not sure how you pass the dynamic values and whats wrong with it. but, you can just create your component like
export interface MyCustomProps {
customProp: string;
}
export interface MyCustomState {
something: string;
}
class MyComponent extends React.Component<MyCustomProps, MyCustomState>{
render(){<div>
... Some content here ...
<div>{this.props.customProp}</div>
</div>}
}
export default MyComponent
and use it in another component like
import MyComponent from './MyComponent';
export class OtherComponent extends React.Component {
render() {
return (
<div>
... Some content here ...
<MyComponent customProp={someDynamicStringValues}/>
</div>
);
}
}
and you can do it recursively
import React from "react";
checkClick = () => {
console.log("clicked");
};
class Test extends React.Component {
render() {
return (
<div>
<button id="button" onClick={this.checkClick}>
click
</button>
</div>
);
}
}
export default Test;
How to click automatically on a button when user coming to page?
Here I want to click automatically above button.
I tried with:
document.getElementById("button").click()
which does not work.
You can use a ref which gives you an instance of the dom element, where you can call the click() method.
If you aren't familiar with refs, you can read all about them here: https://reactjs.org/docs/refs-and-the-dom.html
import React, { Component } from 'react'
class Test extends Component {
constructor(props) {
super(props)
this.button = React.createRef()
}
componentDidMount() {
this.button.current.click()
}
checkClick() {
console.log('clicked')
}
render() {
return (
<div>
<button ref={this.button} onClick={this.checkClick}>Click me!</button>
</div>
)
}
}
export default Test
First of all, I do not recommend you to create functions outside of React component class. In your case, you are not able to use it like this.checkClick because the checkClick function is declared outside of your React component.
The second thing, working with real DOM inside of React is basically, let's say, antipattern. React provides virtual DOM and works with it, so, I recommend you to learn about React ref API.
For your case, you can use the lifecycle componentDidMount() method. It is being called (AUTOMATICALLY, for sure) when the component has finished its first render, so, all refs are already available here and all children elements are beind mounted and present in DOM.
import React from "react"
export default class Test extends React.Component {
componentDidMount() {
document.getElementById("button").click()
}
checkClick() {
console.log("clicked!")
}
render() {
return (
<div>
<button id="button" onClick={this.checkClick}>click</button>
</div>
)
}
}
or, using refs
import React from "react"
export default class Test extends React.Component {
componentDidMount() {
this.button.click()
}
checkClick() {
console.log("clicked!")
}
render() {
return (
<div>
<button ref={button => this.button = button} onClick={this.checkClick}>click</button>
</div>
)
}
}
Use componentDidMount for that,
import React from 'react';
class Test extends React.Component {
componentDidMount(){
this.checkClick();
}
checkClick () {
console.log("clicked");
}
render() {
return (
<div>
<button id="button" onClick={this.checkClick}>click</button>
</div>
)
}
}
export default Test;
I have come across many sources which talk about how to do Component nesting. However, whenever I try to create a Component inside another Component my code fails.
class parent extends React.Component{
class child extends React.Component{
render(){
return <div><h1>Hiiii</h1></div>;
}
}
render(){
return <div><DEF /></div>;
}
}
You can't do that. You can do this on the same file (not same component)
class DEF extends Component {
render() {
return (
<div>
<h1>Hiiii</h1>
</div>
);
}
}
export default class ABC extends Component {
render() {
return (
<div>
<DEF />
</div>
);
}
}
You can't define class inside another class and I don't see why you would want to.
In React you can define Components in two ways: a stateful component (class) or a functional component (function). Stateful components should only be used when you need to manage state locally.
You can do something like:
export default class MyStatefulComponent extends Component() {
render() {
return (
<div><MyFunctionalComponent {...this.props} /></div>
)
}
}
function MyFunctionalComponent(props) {
return <h1>I am functional</h1>
}
I have used the spread operator to pass on the props from the stateful to the functional component, but you should probably pass the individual props as needed..
Comoponent nesting means rendering react components inside other components. Like
<ParentComponent property={value}>
<div>
<ChildComponent />
...
</div>
</ParentComponent>
This is how you can achieve what you are trying to do.
class ABC extends React.Component {
render() {
class DEF extends React.Component {
render() {
return (
<div>
<h1>Hiiii</h1>
</div>
);
}
}
return (
<div>
<DEF />
</div>
);
}
}
Yo can just define component as a static property of other component
class Test extends Component {
static SubTest=props=><div>SubTet</div>
render(){
return(
<div>Test component</div>
)
}
<Test />
<test.SubTest />
So I started with React and I have these two Components.
In the first component I want to iterate an array of objects with the map() function (which works) and call the other component that for now just returns a simple h1 tag.
Well, nothing is been called and there is no error in the console.
I believe the problem is in the return sentence in the renderAvatarData()
(if I do console.log after the return sentence it seems to not get there but if the console.log is before the return it invokes)
HomePageBoxesData.js
import React, { Component } from 'react';
import AvatarDetails from './AvatarDetails';
class HomePageBoxesData extends Component{
constructor(props) {
super(props);
};
renderAvatarData(){
this.props.data.map(data => {
return <AvatarDetails data={data}/>
});
}
render(){
return(
<div>
{this.renderAvatarData()}
</div>
);
}
};
export default HomePageBoxesData;
AvatarDetails.js
import React, { Component } from 'react';
class AvatarDetails extends Component{
constructor(props) {
super(props);
};
render(){
return(
<h1>Hello World</h1>
);
}
};
export default AvatarDetails;
Issue is in renderAvatarData() method, you forgot to use return with map, Use this:
renderAvatarData(){
return this.props.data.map((data)=>{
return <AvatarDetails data={data}/>
});
}
Since you just want to return the Component, you can directly write it like this:
renderAvatarData(){
return this.props.data.map(data => <AvatarDetails data={data} /> );
}
i agree with Mayank Shukla but i usually use this method in this case:
render() {
return(
<div>
_.map(this.props.data, function(value, key){
return(
<AvatarDetails key={key} data={value} />
)
})
</div>
i am not sure if there is one better than the other