simplest approach of dynamically adding components in react - reactjs

currently working on react. I have two components lets say ad and home . Inside home components i have one image and on click event of that image i want to render ad inside home component below image. Is there any simples method . thank you!

check this. i think this is what you want
//dynamically generate div
let DynamicDiv=()=>{
return (<div>
<p>i am here</p>
</div>)
}
class App extends Component {
constructor(props){
super(props)
this.state={
visible:false //visibility of Component
}
this.divVisiblity=this.divVisiblity.bind(this) //function is bind when user clicks on pic
}
divVisiblity(){
//this function will get called when user clicks on function
this.setState(()=>{return {visible:!this.state.visible}}) //changes visible state of Component when user clicks
}
render() {
return (
<div>
<div className="App">
{/* onClick is assigned function named divVisiblity */}
<img onClick={this.divVisiblity} src="https://placekitten.com/g/200/300" alt="test"/>
{/*this is ternary if else statement in js */}
{/* if visible = true ,display Component else dont */}
<div>
{this.state.visible && <DynamicDiv/>}
</div>
);
}
}

I think that will help to you.
export default class HomeComponent extends Component<Props> {
constructor(props) {
super(props);
this.state = {
renderAdComponent: false
};
this.onClickHandler = this.onClickHandler.bind(this);
}
onClickHandler() {
this.setState({renderAdComponent: !this.state.renderAdComponent})
}
render() {
return (
<View>
<Image onClick={this.onClickHandler}/>
{this.state.renderAdComponent ? <AdComponent/> : null}
</View>
);
}
}

What #sdkcy suggested is okay but the ternary operator isn't really needed. You can do the following
{ this.state.isAdShown && <ComponentToShow /> }
This gets rid of the useless : null result.

Related

Props is not showing something on the screen

I am trying to show the number 0 on the screen using props. However nothing shows on the screen and I am not sure why. This is the code:
import React,{Component} from 'react';
import Toolbar from './Toolbar.js';
class Counter extends Component {
constructor(props) {
super(props);
this.state ={
counter:0
}
};
render() {
return(
<div>
{this.state.counter.map(count=>(
<Toolbar count={count}/>
))}
</div>
)
}
};
export default Counter;
And this is where I called it
<div className="toolbar__cart">
<span>{props.count}</span>
<img src="Images/basket.png" alt="Basket" width="40"/></div>
I don't think the map function is applicable here since the value of counter is an integer and not an array. See here for more info on the map function.
If you just want your Toolbar component to display the value of this.state.counter, you could use this:
return(
<Toolbar count={this.state.counter}></Toolbar>
)
And then your Toolbar component would use that counter value like this:
function Toolbar(props) {
return (
<div>
<span>{props.count}</span>
<img src="Images/basket.png" alt="Basket" width="40"/>
</div>
)
}
You are using map function incorrectly.
.map is a function used along with an array
Check out : https://www.w3schools.com/jsref/jsref_map.asp
Correct Code :
render() {
return (
<div>
<Toolbar count={this.state.counter} />
</div>
);
}
You can checkout full code here : https://codesandbox.io/s/naughty-lederberg-hb4wp?file=/src/App.js:203-309
counter.map map function for Arrays - sample
import React,{Component} from 'react';
import Toolbar from './Toolbar.js';
class Counter extends Component {
constructor(props) {
super(props);
this.state ={
counter:[0,1,2]
}
};
render() {
return(
<div>
{this.state.counter.map(count=>(
<Toolbar count={count}/>
))}
</div>
)
}
};

Cannot pass a simplified function to onClick event handler ReactJs

In my React app, I have two Components, Main and Menu Component. Main Component is the parent component of Menu. Menu shows a list of items and upon clicking one of the item, it updates Main's state with the help of a function that I pass as props to Menu. Below is the code for better understanding:
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
dishes: dishes,
selectedDish: null
};
this.selectDish=this.selectDish.bind(this);
}
selectDish(dishId){
this.setState({ selectedDish: dishId});
}
render() {
return (
<div className="App">
<Menu dishes={this.state.dishes} onClick={this.selectDish} />
</div>
);
}
}
export default Main;
And below is the Menu Component:
class Menu extends Component {
constructor(props){
super(props);
this.selectdish=this.selectdish.bind(this);
}
selectdish(dishId){
return this.props.onClick(dishId);
}
render() {
const menu = this.props.dishes.map((dish) => {
return (
<div className="col-12 col-md-5 m-1">
<Card key={dish.id}
onClick={this.selectdish(dish.id)}>
</Card>
</div>
);
});
}
}
export default Menu;
I have omissed some irrelevant parts of the code.
So the workflow should be that when we click over one of dishes rendered by the Menu, that dish's id should be passed back to Main and update the state variable ```selectedDish````, as seen in the method selectDish.
But in the browser console, I get the error Cannot update during existing state transition.
The weird thing is that if I don't pass any dish id and set the selectedDish to a fixed value like 1, everything works fine.
Please help me guys to identify if there is any problem in my event handler, because that is the only part that seems to contain an error.
Thank You!
You are not passing the onClick of the Card a function but you are already calling that function with this.selectdish(dish.id). This will initiate the flow on render, not on click.
You have three options here.
You either wrap that in an additional function like this: onClick={() => {this.selectdish(dish.id)}}>. That way, you are passing a function to the onClick, which is required, and not executing that.
Or you make selectdish return a function like this:
selectdish(dishId){
return () => {this.props.onClick(dishId)};
}
Or you add a name to the card and access the name of the element from the click event:
class Menu extends Component {
constructor(props){
super(props);
this.selectdish=this.selectdish.bind(this);
}
selectdish(event){
return this.props.onClick(event.target.name);
}
render() {
const menu = this.props.dishes.map((dish) => {
return (
<div className="col-12 col-md-5 m-1">
<Card key={dish.id}
name={dish.id}
onClick={this.selectdish}> // this is now the function without calling it
</Card>
</div>
);
});
}
}
export default Menu;
You have some problem in your code:
property key must be define in root <div>
render method in Menu component returns nothing
-
class Menu extends React.Component {
constructor(props) {
super(props);
this.selectdish = this.selectdish.bind(this);
}
selectdish(dishId) {
return this.props.onClick(dishId);
}
render() {
return this.props.dishes.map(dish => {
return (
<div className="col-12 col-md-5 m-1" key={dish.id}>
<div onClick={() => this.selectdish(dish.id)}>{dish.id}</div>
</div>
);
});
}
}
See my playground where I fixed this issues:
https://codesandbox.io/s/react-playground-ib6pr?file=/index.js

How to render only specific components in Reactjs

Is there a way to render only some components in Reactjs
class UserproPage extends Component{
render(){
return(
<>
<Topbar/>
<Navbar/>
<div>
<h1>Hello</h1>
</div>
</>
)
}
The <Navbar/> has menu button that are common to all the pages hence I do not want it to render them every time I click on links on the menu.
you can make a condition in your <Navbar/> component whether you display or not the menu button
example :
class Navbar extends Component {
let display = true;
render() {
return (
<div>This is my component.</div>
{display && <button>menu</button>}
);
}
}
the menu button is displayed only when display variable is true

Clicking the button does not work - React

I use a component called "Modal" that I want to make global so I can use it in any other component. Modal will be used in all the components that need it.
My problem is that now the onclick {this.props.stateModal} in Widgets does not work and show nothing.
This is my Widgets.js
class Widgets extends Component {
render(){
return (
<aside className="widgets">
<div id="bq-datos">
<span>Todas tus campañas</span>
<a onClick={this.props.stateModal} className="content-datos orange" data-bq-datos="999"><div>Llamadas <span>ENTRANTES</span></div></a>
<a className="content-datos violet" data-bq-datos="854"><div>Llamadas <span>SALIENTES</span></div></a>
</div>
{
this.props.isModalOpen
? (
<Modal
stateModal = {this.props.stateModal}
isModalOpen={this.props.isModalOpen} >
<ModalWidgets/>
</Modal>
)
: null
}
<Comunicacion/>
</aside>
);
}
}
I need {this.props.stateModal} to work on my Modal component (in Modal.js)
This is my Modal.js with code for {this.props.stateModal} but not works.
import React, { Component } from 'react';
class Modal extends Component {
constructor(props) {
super(props);
this.state = {
isModalOpen: false,
};
this.stateModal = this.stateModal.bind(this);
}
stateModal() {
this.setState({
isModalOpen: !this.state.isModalOpen
});
alert('¡Ohhhh');
}
render(){
if(this.props.isOpen){
return (
<div id="modal">
{this.props.children}
<ModalWidgets/>
</div>
);
} else {
return null;
}
}
}
class ModalWidgets extends Component {
render(){
if(this.props.isModalOpen){
return(
<article id="md-descansos" className="medium">
hola tú!!
</article>
);
}
else{
return(
<div>k pasa!</div>
);
}
}
}
export default Modal;
I think that i need do something in my Modal.js but i don't know what it is
Edit:
I have changed the components to use Modal as the parent of all the other Modal that I want to use, such as ModalWidgets. But now when you click on the button of {this.props.stateModal} in Widgts not works.
Thanks!
You have to use stateModal function somewhere in your Modal component. Something like:
render(){
if(this.props.isOpen){
return (
<ModalGenerico>
<div id="modal">
<button type="button" onClick={this.stateModal}>Click here</button>
{this.props.children}
</div>
</ModalGenerico>
);
} else {
return <ModalGenerico />;
}
}
The button in the example above should be replaced with your backdrop of the modal (or anything else as you like).
Edited: You should take a look at this article State vs Props. Because I notice that you weren't clear the usage of them.
Besides, I don't think there's such thing called global component as you described. Every components in react are reusable and can be imported anywhere in the project.

Rendering an image in React from this.props

I have an react application, that I created with Create-React-App. My objective is when a user clicks on an image, the image changes. So, I want the image to come from the props.
For some reason, this code does not work.
<img alt="mug shot" src={this.props.photo} />
However, this works
<img alt="mug shot" src={require('../../Assets/Photos/Four.png')}/>
What am I doing wrong here?
I assume you are bundling your app using Webpack. Probably, you might be using a file-loader/url-loader to process the image. So, when you require something that ends with image file extension, webpack runs the contents of that file through this loader. For more information, check https://survivejs.com/webpack/loading/images/
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
img:'https://www.codeproject.com/KB/GDI-plus/ImageProcessing2/img.jpg'
}
this.changeImg = this.changeImg.bind(this);
}
changeImg() {
this.setState({
img:'http://www.apicius.es/wp-content/uploads/2012/07/IMG-20120714-009211.jpg'
})
}
render() {
return(
<div>
<ImageChande change={this.changeImg} src={this.state.img} />
</div>
);
}
}
class ImageChande extends React.Component {
render() {
return(
<div>
<img onClick={this.props.change} alt="something" src={this.props.src} />
</div>
);
}
}

Resources