I am new in ReactJs and trying to create a popup window through onclick event.
I am following this resource - https://dev.to/skptricks/create-simple-popup-example-in-react-application-5g7f
File - /src/components/feed.js
import React from 'react';
function feed (props) {
return (
<div className="card-header">
<h2>{props.firstname} {props.middleInitial} {props.lastname}</h2>
<h4 className="card-title">{props.gender}</h4>
</div>
<div className="card-footer">
<button onClick="" className="btn btn-secondary">Click To view Samples</button>
</div>
);
}
export default feed;
File - /src/app.js
import React, { Component } from 'react';
import './App.css';
import Header from './components/header.js';
import fetchfeed from './components/fetchfeed.js';
class App extends Component {
render() {
return (
<div>
<Header />
<div className="d-flex justify-content-center">
<fetchfeed />
</div>
</div>
);
}
}
export default App;
File - /src/components/fetchfeed.js
import React from 'react';
import axios from 'axios';
import Pagination from "react-js-pagination";
import feed from './feed.js';
class fetchfeed extends React.Component {
constructor(props) {
super(props);
this.state = {
feedDetails: []
};
this.fetchURL = this.fetchURL.bind(this);
}
fetchURL() {
axios.get(`/feed/`)
.then( response => {
..............
});
//Fetch the feed url and process the variables and setstate to feedDetails array.
}
componentDidMount () {
this.fetchURL()
}
populateRowsWithData = () => {
const feedData = this.state.feedDetails.map(feed => {
return <feed
key = {feed.id}
firstname = {feed.firstname}
middleInitial = {feed.middleInitial}
lastname = {feed.lastname}
dateOfBirth = {feed.dateString}
gender = {feed.gender}
/>;
});
return feedData
}
render(){
return (
<div >
{this.populateRowsWithData()}
</div>
);
}
}
export default fetchfeed;
I have already created Popup.js under /src/components and the required css for the popup as directed on reference link.
My question is where should I define the onclick function for popup?
Any help is highly appreciated. Thanks in advance.
As it says in the source you should do something like this in the component you want to show the popup in:
//This is the function
togglePopup() {
this.setState({
showPopup: !this.state.showPopup
});
}
// This is what you should do in the render method
{this.state.showPopup ?
<Popup
text='Click "Close Button" to hide popup'
closePopup={this.togglePopup.bind(this)}
/>
: null
}
As per my understanding, you are trying to customize the code in the tutorial according to your requirements. If you want to open the popup on click of the button "click to view samples", you should do two things first.
Define a function to trigger when button is clicked
Attach that function to the button
The following code demonstrates above steps.
import React from 'react';
function feed (props) {
function openPopup(){
//code relevant to open popup
}
return (
<div className="card-header">
<h2>{props.firstname} {props.middleInitial} {props.lastname}</h2>
<h4 className="card-title">{props.gender}</h4>
</div>
<div className="card-footer">
<button onClick={openPopup} className="btn btn-secondary">Click To view Samples</button>
</div>
);
}
export default feed;
Related
import React, { Component } from 'react';
import { OverlayCartContainer,OverlayCartHeader,TotalContainer,
ActionSection,ViewBagButton,CheckoutButton,OverlayContainerWrapper,} from './OverlayCartStyle';
import { Link } from 'react-router-dom'
import { connect } from 'react-redux';
import { OverlayCartbody } from '../../';
export class OverlayCartWrapperContainer extends Component {
constructor(){
super();
this.state={
ref: React.createRef(null),
actionRef: React.createRef(null),
}
}
render() {
return (
<OverlayContainerWrapper > <OverlayCartContainer ref={this.state.ref}>
<OverlayCartHeader>
My Bag, <span>{getTotalItem()} items</span>
</OverlayCartHeader>
<OverlayCartbody cartItem ={this.props.cart}/>
<TotalContainer>
<p>Total</p>
<h6>{this.props.currencySymbol} {getTotalPrice(this.props.currencyState)}</h6>
</TotalContainer>
<ActionSection >
<Link to={"/cart"}><ViewBagButton onClick={(e)=>{this.props.toggleCart(e)}}>VIEW BAG</ViewBagButton></Link>
<CheckoutButton>CHECKOUT</CheckoutButton>
</ActionSection>
</OverlayCartContainer></OverlayContainerWrapper>
)
}
}
const mapStateToProps = (state) =>{
return {
currencyState:state.currency.currencyState,
currencySymbol:state.currency.currencySymbol,
cart:state.cart.cart.cartItems
}
}
export default connect(mapStateToProps)(OverlayCartWrapperContainer);
Here in the <ActionSection ><Link to={"/cart"}><ViewBagButton onClick={(e)=>{this.props.toggleCart(e)}}>VIEW BAG</ViewBagButton></Link<CheckoutButton>CHECKOUT</CheckoutButton></ActionSection>
I want when i click on view bag it redirect to cart view page it should go to cart page but the onclick function is rendering . i also want that onclick function run but page also redirect please help me how to do it this onClick={(e)=>{this.props.toggleCart(e)}} onclick should run but it also go to the next page
Is your App/Component wrapped in react-router? if not don't use Link.
Simple solution i can think of is replace your Link with div and then your onClick function will work and in the end of onClick function code, you can use history.push('/cart')
<div>
<ViewBagButton onClick={this.props.toggleCart}>
VIEW BAG
</ViewBagButton>
</div>
const toggleCart = (e) => {
// your code...
// at the end
history.push('/cart');
// you can get the history from props or can use useHistory hook
}
I am struggling with figuring out how to implement conditional rendering in React. Basically, what I want to do is this: if there is a reviewResponse in the reviewResponses array, I no longer want to render the reviewResponseForm. I only want to render that ReviewResponse. In other words, each review can only have one response in this app.
I am not sure what I am doing wrong when trying to implement this logic. I know I need to implement some kind of conditional statement saying if the length of my reviewResponses array is greater than 0, I need to render the form. Otherwise, I need to render that reviwResponse. Every statement I have written has not worked here. Does anybody have a suggestion?
Here is my code so far:
My review cardDetails component renders my ReviewResponseBox component and passed the specific reviewId as props:
import React from "react";
import { useLocation } from "react-router-dom";
import StarRatings from "react-star-ratings";
import ReviewResponseBox from "../ReviewResponse/ReviewResponseBox";
const ReviewCardDetails = () => {
const location = useLocation();
const { review } = location?.state; // ? - optional chaining
console.log("history location details: ", location);
return (
<div key={review.id} className="card-deck">
<div className="card">
<div>
<h4 className="card-title">{review.place}</h4>
<StarRatings
rating={review.rating}
starRatedColor="gold"
starDimension="20px"
/>
<div className="card-body">{review.content}</div>
<div className="card-footer">
{review.author} - {review.published_at}
</div>
</div>
</div>
<br></br>
{/*add in conditional logic to render form if there is not a response and response if there is one*/}
<ReviewResponseBox review_id={review.id}/>
</div>
);
};
export default ReviewCardDetails;
Then eventually I want this component, ReviewResponseBox, to determine whether to render the responseform or the reviewresponse itself, if it exists already.
import React from 'react';
import ReviewResponse from './ReviewResponse';
import ReviewResponseForm from './ReviewResponseForm';
class ReviewResponseBox extends React.Component {
constructor() {
super()
this.state = {
reviewResponses: []
};
}
render () {
const reviewResponses = this.getResponses();
const reviewResponseNodes = <div className="reviewResponse-list">{reviewResponses}</div>;
return(
<div className="reviewResponse-box">
<ReviewResponseForm addResponse={this.addResponse.bind(this)}/>
<h3>Response</h3>
{reviewResponseNodes}
</div>
);
}
addResponse(review_id, author, body) {
const reviewResponse = {
review_id,
author,
body
};
this.setState({ reviewResponses: this.state.reviewResponses.concat([reviewResponse]) }); // *new array references help React stay fast, so concat works better than push here.
}
getResponses() {
return this.state.reviewResponses.map((reviewResponse) => {
return (
<ReviewResponse
author={reviewResponse.author}
body={reviewResponse.body}
review_id={this.state.review_id} />
);
});
}
}
export default ReviewResponseBox;
Here are the ReviewResponseForm and ReviewResponse components:
import React from "react";
class ReviewResponseForm extends React.Component {
render() {
return (
<form className="response-form" onSubmit={this.handleSubmit.bind(this)}>
<div className="response-form-fields">
<input placeholder="Name" required ref={(input) => this.author = input}></input><br />
<textarea placeholder="Response" rows="4" required ref={(textarea) => this.body = textarea}></textarea>
</div>
<div className="response-form-actions">
<button type="submit">Post Response</button>
</div>
</form>
);
}
handleSubmit(event) {
event.preventDefault(); // prevents page from reloading on submit
let review_id = this.review_id
let author = this.author;
let body = this.body;
this.props.addResponse(review_id, author.value, body.value);
}
}
export default ReviewResponseForm;
import React from 'react';
class ReviewResponse extends React.Component {
render () {
return(
<div className="response">
<p className="response-header">{this.props.author}</p>
<p className="response-body">- {this.props.body}</p>
<div className="response-footer">
</div>
</div>
);
}
}
export default ReviewResponse;
Any advice would be helpful, thank you.
If I understand your question correctly, you want to render ReviewResponseForm if the this.state.reviewResponses state array is empty.
Use the truthy (non-zero)/falsey (zero) array length property to conditionally render either UI element.
render () {
const reviewResponses = this.getResponses();
const reviewResponseNodes = <div className="reviewResponse-list">{reviewResponses}</div>;
return(
<div className="reviewResponse-box">
{reviewResponses.length
? (
<>
<h3>Response</h3>
{reviewResponseNodes}
</>
)
: (
<ReviewResponseForm addResponse={this.addResponse.bind(this)}/>
)}
</div>
);
}
I am aiming to create a component containing a function, in which a button removes a separate div containing text, which is presented in React.js by another component in a separate div.
Below is the code for my app.js. I would like to set the style of "tweetSection" to "none" (contains Tweet component that provides the text), using the "TurnOff" component.
import logo from './logo.svg';
import Tweet from './Tweet';
import TurnOff from './TurnOff';
function App() {
return (
<div>
<div id="tweetSection">
<Tweet />
</div>
<div id="button">
<TurnOff />
</div>
</div>
);
}
export default App;```
Here is the code for my TurnOff component
import React from 'react';
function TurnOff(){
const toggle = () => {
document.getElementById('tweetSection').style.display = "none";
}
return(
<div>
<button onClick={toggle()}>this is a button</button>
</div>
);
}
export default TurnOff;
When I run this, I get a type error stating "TypeError: Cannot read property 'style' of null". Is there a simplistic way, or program this in a different manner in order to hide the "tweetSection" div?
A few things.
To answer why you are getting the error, it is because you are calling the function (toggle()) immeaditely with onClick={toggle()}.
Use this to avoid the problem of calling the function too early:
<button onClick={toggle}>this is a button</button>
Or:
<button onClick={() => toggle()}>this is a button</button>
It is being called as soon as it renders, which means document.getElementById('tweetSection') might be null.
You can check for this like:
const el = document.getElementById('tweetSection');
if (el) {
el.style.display = "none";
} else {
console.warn('No tweetSection element found');
}
However, a more react way to solve this problem would be to pass props:
import logo from './logo.svg';
import Tweet from './Tweet';
import TurnOff from './TurnOff';
import React, {useState} from 'react';
function App() {
const [showTweet, setShowTweet] = useState(true);
return (
<div>
{showTweet && <div id="tweetSection">
<Tweet />
</div>}
<div id="button">
<TurnOff toggle={() => {
setShowTweet(!showTweet);
}}
/>
</div>
</div>
);
}
export default App;
import React from 'react';
function TurnOff({ toggle }){
return(
<div>
<button onClick={toggle}>this is a button</button>
</div>
);
}
export default TurnOff;
I have a minimalist landing page with two texts and one div, containing two buttons. On click of one of those buttons, I want to render the App component.
Here's what I've tried so far:
import React from 'react';
import App from '../App';
export default class Landing extends React.Component {
constructor(){
super();
}
launchMainWithoutProps = () => {
return (<App />)
};
showAppMain =() => {
console.log('Silk board clicked');
this.launchMainWithoutProps();
};
render() {
return (
<div className='landing'>
<div className="centered">
<div className="introText">
<h3>Welcome to KahanATM</h3>
<h5>A Simple Web App with React to find ATMs closest to you (3km radius) or from Silk Board Flyover</h5>
</div>
<div className="buttonsLayout">
<button
className='getLocation'
onClick={this.showAppMainWithLocation}>
Get My Location
</button>
<button
className='silkBoard'
onClick={this.showAppMain}>
Central Silk Board
</button>
</div>
</div>
</div>
);
}
}
But when the button is clicked only the log is shown in console. How can I do this with or without react-router as I think this is too small to implement routes in. Thanks.
Use a boolean flag in your state. When you click and execute showAppMain set your state variable to true, which causes your render function to return <App /> instead:
import React from 'react';
import App from '../App';
export default class Landing extends React.Component {
constructor() {
super();
this.state = {
shouldShowMain: false,
};
this.showAppMain = this.showAppMain.bind(this);
}
showAppMain() {
console.log('Silk board clicked');
this.setState({shouldShowMain: true});
};
render() {
if (this.state.shouldShowMain) {
return (<App />);
}
return (
<div className='landing'>
<div className="centered">
<div className="introText">
<h3>Welcome to KahanATM</h3>
<h5>A Simple Web App with React to find ATMs closest to you (3km radius) or from Silk Board Flyover</h5>
</div>
<div className="buttonsLayout">
<button
className='getLocation'
onClick={this.showAppMainWithLocation}>
Get My Location
</button>
<button
className='silkBoard'
onClick={this.showAppMain}>
Central Silk Board
</button>
</div>
</div>
</div>
);
}
}
I am creating a basic blog in react using Flux + React Router + Firebase. I am having trouble trying to get a single blog post to render. When I click on the link to a single post, I try to filter out all of the other posts from a list of all posts and display only a single post from my firebase database.
I attempt to do this by matching the key of the firebase entry with the url params like so if (this.props.routeParams.key===key) . I really do not know what I have to do to make this happen. Any suggestions are welcome.
Below is Blogger.jsx, the page where I allow a user to create a blog post and then beneath the blog post, I display a list of the titles all blog posts.
import AltContainer from 'alt-container';
import React from 'react';
import { Link } from 'react-router';
import List from './List.jsx'
import Firebase from 'firebase'
import BlogStore from '../stores/BlogStore'
import BlogActions from '../actions/BlogActions';
const rootURL = 'https://incandescent-fire-6143.firebaseio.com/';
export default class Blogger extends React.Component {
constructor(props) {
super(props);
BlogStore.getState();
BlogStore.mountFirebase();
{console.log(this.props.location.query)}
};
componentDidMount() {
BlogStore.listen((state) => {
this.setState(state)
})
this.firebaseRef = new Firebase(rootURL + 'items/');
}
componentWillMount() {
BlogStore.unlisten((state) => {
this.setState(state)
})
}
renderList = (key) => {
return (
<Link to={`blogshow/${key}`}> <List key={key} blog={this.state.blog[key]} /> </Link>
)
}
handleInputChange = () => {
BlogStore.setState({
title: this.refs.title.value,
text: this.refs.text.value});
}
handleClick = () => {
BlogStore.handleClick();
}
render() {
return (
<div>
<div className="row panel panel-default">
<div className="col-md-8 col-md-offset-2">
<h2>
Create a New Blog Post
</h2>
</div>
</div>
<h2>Blog Title</h2>
<div className="input-group">
<input
ref="title"
value={BlogStore.state.title}
onChange = {this.handleInputChange}
type="text"
className="form-control"/>
<span className="input-group-btn">
</span>
</div>
<h2>Blog Entry</h2>
<div className="input-group">
<textarea
ref="text"
value={BlogStore.state.text}
onChange = {this.handleInputChange}
type="text"
className="form-control"/>
</div>
<div className="blog-submit input-group-btn">
<button onClick={this.handleClick}
className="btn btn-default" type="button">
Publish Blog Post
</button>
</div>
{/*<List blog={this.state.blog} />*/}
{Object.keys(BlogStore.state.blog)
.map(this.renderList)}
</div>
);
}
}
When a user clicks on a link to a single blog post, they should be transported to a page which shows only that single blog post. I have called this component BlogShow. I can't get BlogShow to render because I keep on getting the error
invariant.js?4599:45 Uncaught Invariant Violation: BlogShow.render(): A
valid React element (or null) must be returned. You may have returned
undefined, an array or some other invalid object.
This is BlogShow.jsx:
import AltContainer from 'alt-container';
import React from 'react';
import { Link } from 'react-router';
import Blogger from './Blogger'
import List from './List'
const rootURL = 'https://incandescent-fire-6143.firebaseio.com/';
import BlogStore from '../stores/BlogStore'
import BlogActions from '../actions/BlogActions';
export default class BlogShow extends React.Component {
constructor(props) {
super(props);
{console.log(this.props.routeParams.key)}
this.filterList = this.filterList.bind(this);
}
filterList(key) {
if (this.props.routeParams.key===key) {
return (<List key={key} blog={BlogStore.state.blog[key]} />)
}
}
render() {
<div> {Object.keys(BlogStore.state.blog).map(this.filterList)} </div>
}
}
You are getting that error because your Component BlogShow is not returning anything.
render() {
<div> {Object.keys(BlogStore.state.blog).map(this.filterList)} </div>
}
Should be:
render() {
return <div> {Object.keys(BlogStore.state.blog).map(this.filterList)} </div>
}
I'm not familiar with React.js at all, but I am familiar with pure JS arrays. To remove elements from an array, you should use .filter(), and then afterwards you can map the items.
Something like this:
filterList(key) {
return this.props.routeParams.key === key; // true if the item should stay in the list
}
mapList(key) {
return <List key={key} blog={BlogStore.state.blog[key]} />;
}
render() {
return <div> {Object.keys(BlogStore.state.blog).filter(this.filterList).map(this.mapList)} </div>;
}