Why is this <div> style not working in my Component - reactjs

I´m a bit new to React and cant get this marginTop to work:
const pStyle = {
marginTop: '40px'
};
nothing happens when I apply it in the div and I think I missed something please advice
import React, { Component } from "react";
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
/* Import Components */
import Input from "../components/input/Input";
import Button from "../components/button/Button";
import { actionCreators } from '../store/ContainerReducer';
const pStyle = {
marginTop: '40px'
};
class FormContainer extends Component {
constructor(props) {
super(props);
this.state = {
localBook: {
title: "",
author: "",
genre: "",
price: ""
},
};
this.handleTitle = this.handleTitle.bind(this);
this.handleAuthor = this.handleAuthor.bind(this);
this.handleGenre = this.handleGenre.bind(this);
this.handlePrice = this.handlePrice.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleClearForm = this.handleClearForm.bind(this);
}
/* This lifecycle hook gets executed when the component mounts */
handleTitle(e) {
let value = e.target.value;
this.setState(
prevState => ({
localBook: {
...prevState.localBook,
title: value
}
}),
() => console.log(this.state.localBook)
);
}
handleAuthor(e) {
let value = e.target.value;
this.setState(
prevState => ({
localBook: {
...prevState.localBook,
author: value
}
}),
() => console.log(this.state.localBook)
);
}
handleGenre(e) {
let value = e.target.value;
this.setState(
prevState => ({
localBook: {
...prevState.localBook,
genre: value
}
}),
() => console.log(this.state.localBook)
);
}
handlePrice(e) {
let value = e.target.value;
this.setState(
prevState => ({
localBook: {
...prevState.localBook,
price: value
}
}),
() => console.log(this.state.localBook)
);
}
handleFormSubmit(e) {
e.preventDefault();
this.props.requestBooks(this.state.localBook);
}
handleClearForm(e) {
e.preventDefault();
this.setState({
localBook: {
title: "",
author: "",
genre: "",
price: ""
}
});
}
render() {
return (
<div class="pStyle">
<form className="container-fluid" onSubmit={this.handleFormSubmit}>
<Input
inputType={"text"}
title={"Title"}
name={"title"}
value={this.state.localBook.title}
placeholder={"Enter Title"}
handleChange={this.handleTitle}
/>{" "}
{/* Title */}
<Input
inputType={"text"}
title={"Author"}
name={"author"}
value={this.state.localBook.author}
placeholder={"Enter Author"}
handleChange={this.handleAuthor}
/>{" "}
{/* Author */}
<Input
inputType={"text"}
title={"Genre"}
name={"genre"}
value={this.state.localBook.genre}
placeholder={"Select Genre"}
handleChange={this.handleGenre}
/>{" "}
{/* Genre */}
<Input
inputType={"text"}
title={"Price"}
name={"price"}
value={this.state.localBook.price}
placeholder={"Select Price"}
handleChange={this.handlePrice}
/>{" "}
{/* Price */}
<Button
action={this.handleFormSubmit}
type={"primary"}
title={"Submit"}
style={buttonStyle}
/>{" "}
{/*Submit */}
<Button
action={this.handleClearForm}
type={"secondary"}
title={"Clear"}
style={buttonStyle}
/>{" "}
{/* Clear the form */}
</form>
</div>
);
}
}
const buttonStyle = {
margin: "10px 10px 10px 10px"
};
export default connect(
null,
dispatch => bindActionCreators(actionCreators, dispatch)
)(FormContainer);
I have this App.js
import React from 'react';
import { Route } from 'react-router';
import Layout from './components/Layout';
import Posts from './components/Posts';
import FormContainer from './components/FormContainer';
import 'typeface-roboto';
export default () => (
<Layout>
<Route exact path='/' component={FormContainer} />
<Route exact path='/' component={Posts} />
</Layout>
);
I have this Layout.js
import React from 'react';
import { Container } from 'reactstrap';
import '../../node_modules/primereact/resources/primereact.css';
import '../../node_modules/primereact/resources/themes/nova-dark/theme.css';
import NavMenu from './NavMenu';
export default props => (
<div>
<NavMenu />
<Container>
{props.children}
</Container>
</div>
);

you have to set your style to the div
<div style={pStyle}>
</div>

You should add your style not by using class keyword, but by using style keyword. And you should wrap it in curly braces, because pStyle is a JSX constant, not a string.
P.S.: Also, in React you should use className instead of class. Just FYI.
Here is how things should work in your case:
<div style={pStyle}>
<form className="container-fluid" onSubmit={this.handleFormSubmit}>
<Input
inputType={"text"}
title={"Title"}
name={"title"}
value={this.state.localBook.title}
placeholder={"Enter Title"}
handleChange={this.handleTitle}
/>{" "}
{/* Title */}
<Input
inputType={"text"}
title={"Author"}
name={"author"}
value={this.state.localBook.author}
placeholder={"Enter Author"}
handleChange={this.handleAuthor}
/>{" "}
{/* Author */}
<Input
inputType={"text"}
title={"Genre"}
name={"genre"}
value={this.state.localBook.genre}
placeholder={"Select Genre"}
handleChange={this.handleGenre}
/>{" "}
{/* Genre */}
<Input
inputType={"text"}
title={"Price"}
name={"price"}
value={this.state.localBook.price}
placeholder={"Select Price"}
handleChange={this.handlePrice}
/>{" "}
{/* Price */}
<Button
action={this.handleFormSubmit}
type={"primary"}
title={"Submit"}
style={buttonStyle}
/>{" "}
{/*Submit */}
<Button
action={this.handleClearForm}
type={"secondary"}
title={"Clear"}
style={buttonStyle}
/>{" "}
{/* Clear the form */}
</form>
</div>

Related

How to update props of child to child component

So im trying to pass some props from my login component to the payment component with the user's info, to do this I update as shown below:
import React, { Component } from 'react';
import Login from './login';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Pay from './payment';
export default class app extends Component {
constructor(props) {
super(props);
this.state = {
LoggedInState: false,
LoggedInUser: [],
SellingProduct: [],
Users: [],
generalproducts: []
}
}
render() {
return (
<BrowserRouter>
<NavBar logged={this.state.LoggedInUser} />
<div className="container-fluid">
<Routes>
<Route path='/' element={<HomePage products={this.generalproducts} />} />
<Route path='/shoppingcart' element={<ShopCart logged={this.state.LoggedInState} paymentHandle={this.onBuyFromCart} products={this.state.generalproducts} />} />
<Route path='/login' element={<Login onLogged={this.onLogInSuccesful} />} />
<Route path='/Payment' element={<Pay ProductInProcess={this.state.SellingProduct} user={this.state.LoggedInUser} />} />
<Route path='/Camera' element={<Cam />} />
<Route path='*' element={<Nomatch />} />
</Routes>
</div>
</BrowserRouter>
)
}
onBuyFromCart = (prod) => {
console.log('in');
this.setState({ SellingProduct: prod });
console.log('dada');
}
onLogInSuccesful = (userlogged) => {
this.setState({ LoggedInState: true, LoggedInUser: userlogged });
console.log('AppLoggedinState', this.state.LoggedInState);
console.log('AppLoggedinuser', this.state.LoggedInUser);
};
componentDidMount = async () => {
var response = await fetch("http://localhost:5000/products");
var ConvertedProducts = await response.json();
this.setState({ generalproducts: ConvertedProducts });
}
}
It works fine from login component to the parent component but when payment tab is displayed I get no values using props, for example:
import React, { Component } from "react";
import { Link } from "react-router-dom";
export default class Pay extends Component {
constructor(props) {
super(props);
this.state = {
productSaled: this.props.ProductInProcess,
info: [],
stored: false
};
}
render() {
return (
<button className="card p-3" onClick={() => { this.onStoredCardClick(); }}>
<div className="img-box">
<img src="https://www.freepnglogos.com/uploads/mastercard-png/file-mastercard-logo-svg-wikimedia-commons-4.png"
alt="" />
</div>
<div className="number">
<label className="fw-bold">{this.props.user.CreditCardnum}</label>
</div>
<div className="d-flex align-items-center justify-content-between">
<small><span className="fw-bold">Expiry date:</span><span>{this.props.user.CreditCardDate}</span></small>
<small><span className="fw-bold">Name:</span><span>{this.props.user.CreditCardName}</span></small>
</div>
</button>
);
}
onStoredCardClick = () => {
this.setState({ stored: true });
console.log('state ', this.state);
console.log(' props', this.props);
}
componentDidMount = () => {
console.log(this.state);
}
}
gives me nothing as seen here:payment info
And login component is:
import React, { Component } from "react";
export default class Login extends Component {
constructor(props) {
super(props);
this.state = { email: "", password: "", message: "" };
}
render() {
return (
<div>
<h4 className="m-1 p-2 border-bottom">Login</h4>
{/* Email starts */}
<div className="form-group form-row">
<label className="col-lg-4">Email:</label>
<input
type="text"
className="form-control"
value={this.state.email}
onChange={(event) => {
this.setState({ email: event.target.value });
}}
/>
</div>
{/* Email ends */}
{/* Password starts */}
<div className="form-group form-row">
<label className="col-lg-4">Password:</label>
<input
type="password"
className="form-control"
value={this.state.password}
onChange={(event) => {
this.setState({ password: event.target.value });
}}
/>
</div>
{/* Password ends */}
<div className="text-right">
{this.state.message}
<button className="btn btn-primary m-1" onClick={this.onLoginClick}>
Login
</button>
</div>
</div>
);
} //end of render
//Executes when the user clicks on Login
onLoginClick = async () => {
var response = await fetch(
`http://localhost:5000/users?id=${this.state.email}&password=${this.state.password}`,
{ method: "GET" }
);
var body = await response.json();
if (body.length > 0) {
//success
var response = await fetch(
`http://localhost:5000/users/${this.state.email}`,
{ method: "GET" }
);
var body = await response.json();
console.log(body);
this.setState({
message: <span className="text-success">Successfully Logged-in</span>,
});
this.props.onLogged(body);
//window.location = '\payment';
} else {
//error
this.setState({
message: (
<span className="text-danger">Invalid login, please try again</span>
),
});
}
};
}
this is the console log form AppState
And this is the console log from Payment
Well, after a couple months I found out that when using window.locaionthe page will refresh al previous values for the props given, therefore, nothing will arrive to the component being loaded. To prevent this I changed to the usage of useNavigate and the hook useContext this solved the shortage of arriving information to the other children components. I am not good with the terminology of react yet so excuse for it.
The log in component now look like this (please focus on the useNavigate and useContext as for it is what solved my error):
import React, { Component, useState, useContext } from "react";
import { UserContext } from "./UserContext";
import { useNavigate } from "react-router-dom";
export default function Login(props) {
const [State, setState] = useState({
Email: "",
password: "",
message: "",
});
const history = useNavigate();
const [GeneralState, setGeneralState] = useContext(UserContext);
let onLoginClick = async () => {
const response1 = await fetch(
`http://localhost:5000/users?id=${State.Email}&password=${State.password}`,
{ method: "GET" }
);
const body1 = await response1.json();
if (body1.length > 0) {
//success
const response = await fetch(
`http://localhost:5000/users/${State.Email}`,
{ method: "GET" }
);
const body = await response.json();
setState({
message: <span className="text-success">Successfully Logged-in</span>,
});
setGeneralState({
...GeneralState,
LoggedInState: true,
LoggedInUser: body,
})
history("/shoppingcart", { replace: true });
} else {
//error
setState({
message: (
<span className="text-danger">Invalid login, please try again</span>
),
});
}
};
return (
<div>
<h4 className="m-1 p-2 border-bottom">Login</h4>
{/* Email starts */}
<div className="form-group form-row">
<label className="col-lg-4">Email:</label>
<input
type="text"
className="form-control"
value={State.Email}
onChange={(event) => {
setState({ ...State, Email: event.target.value });
}}
/>
</div>
{/* Email ends */}
{/* password starts */}
<div className="form-group form-row">
<label className="col-lg-4">password:</label>
<input
type="password"
className="form-control"
value={State.password}
onChange={(event) => {
setState({ ...State, password: event.target.value });
// console.log(GeneralState)
}}
/>
</div>
{/* password ends */}
<div> <a href="/register" style={{ fontSize: 12 }}>No tienes cuenta? Registrate</a></div>
<div className="text-right">
{State.message}
<button className="btn btn-primary m-1" onClick={onLoginClick}>
Login
</button>
</div>
</div>
);
//Executes when the user clicks on Login
}
And the UserContext component, from where useContext takes the info, is this one:
import { createContext } from "react";
export const UserContext = createContext();
As for the other components like app component, shown in the question statement at the start of this thread, it is necessary to also add the useContext statements so that your whole project will work under the same context.

React.js onclick button in one component change effect in other component

js
I have two buttons in parent component e.g button1 ,button2 ,and
I have two radio button in my child component e.g radio1,radio2 ,and both have class to active yellow
the task i need to do is onclick button1 in the parent component, the radio1 become active class and same on click on button2, radio2 in child become active class
import React ,{Component} from 'react';
import { withStyles } from '#material-ui/core/styles';
import { Radio } from '#material-ui/core';
import "react-datepicker/dist/react-datepicker.css";
import { connect } from 'react-redux';
import "./strip.css";
import * as actions from '../../actions/instruction';
import PaypalPayment from "./PaypalPayment"
import BankPayment from "./BankPayment"
class WidthdrawPayment extends Component {
state={
open: false,
cardId: 0,
}
setButton = (id) => {
this.setState({ cardId: id });
}
handlesChange = ({ id }) => {
//const { cardId } = this.props;
this.setState({ cardId: id });
};
render() {
const { open,cardId } = this.state;
return (
<>
<div className="main">
<div className="container-fluid no-padding">
<div style={{display: 'flex'}} >
<div
className=" lawyer-payment-big-box row">
<div className="col-md-12">
<div
className={cardId === 1 ? "active-div widthdraw-payment-choose-box col-sm-4 col-md-4 col-lg-4" :"widthdraw-payment-choose-box col-sm-4 col-lg-4 col-md-4"}>
<span>
<Radio
style={{color:'#fff'}}
color="primary"
checked={cardId === 1}
onClick={() => this.setButton(1)}
onChange={() => this.handlesChange({ id: 1 })}
name="radio-button-demo"
/>
</span>
<span className="widthdraw-payment-type-font" >Transfer</span>
</div>
<div
className={cardId === 2 ? "active-div widthdraw-payment-choose-box col-sm-4 col-md-4 col-lg-4" :"widthdraw-payment-choose-box col-sm-4 col-md-4 col-lg-4"}>
<span>
<Radio
style={{color:'#fff'}}
className=""
color="primary"
checked={cardId === 2}
onClick={() => this.setButton(2)}
onChange={()=> this.handlesChange({ id: 2 })}
name="radio-button-demo"
/>
</span>
<span className="widthdraw-payment-type-font">Bank Transfer</span>
</div>
<div className="col-md-4"></div>
</div>
{cardId === 0 ?
<div className="row">
<div style={{padding:'30px'}} className="col-md-12">
<p>Please select your payment method first to proceed</p>
</div>
</div>
:
<>
{
cardId ===1 ?
<>
{cardId ===1 &&
<PaypalPayment
{...this.props}
{...this.state}
/>
}
</>
:
<>
{/* <BankPayment
{...this.props}
{...this.state}
/> */}
{cardId ===2 ?
<>
{cardId===2 &&<BankPayment
{...this.props}
{...this.state}
/>
}
</>
:
<>
<div className="row">
<div style={{padding:'30px'}} className="col-md-12">
<p>Please select your payment method first to proceed</p>
</div>
</div>
</>
}
</>
}
</>
}
</div>
</div>
</div>
</div>
</div>
</>
)
}
}
export default WidthdrawPayment
import React from 'react';
import { withStyles } from '#material-ui/core/styles';
import { KeyboardDatePicker, MuiPickersUtilsProvider } from "#material-ui/pickers";
import DateFnsUtils from '#date-io/date-fns';
import {Link,Redirect} from 'react-router-dom';
import { Button, TYPES } from "../../components/atoms/YellowButton";
import { connect } from 'react-redux';
import moment from 'moment';
import * as actions from '../../actions/instruction';
import { EmptyList } from '../../components/molecules/NotFound/EmptyView';
import WidthdrawPayment from '../WidthdrawPayment'
const drawerWidth = 550;
class FirmPaymentStats extends React.Component {
constructor(props) {
super(props);
this.state={
open: false,
buttonId: 1,
cardId: 0,
}
this.superheroElement = React.createRef();
}
handlePaypalPayment = () => {
const {history} = this.props;
this.defaultactivepaypal()
history.push(`/main/dashboardmaster/widthdrawpayment`)
}
handleBankPayment = () => {
const {history} = this.props;
this.defaultActivebank()
history.push(`/main/dashboardmaster/widthdrawpayment`)
}
defaultactivepaypal = () => {
const {cardId} = this.props;
this.setState({ cardId: 1 });
}
defaultActivebank = () => {
const {cardId} = this.props;
this.setState({ cardId: 2 });
}
render() {
const { history,cardId } = this.props;
const { open,cardId } = this.state;
return (
<div className='main'>
<div className='container-fluid no-padding'>
<div className={classes.root}>
<div className="firm-payment-history-box row">
<div className='admin-options-section cases-section row'>
{/* balance bar */}
<div style={{ padding: '0px 30px' }} className="row">
<div class="lawyer-payment-subheading">
<div >
<p className="system-ui-bold-text firm-payment-main-heading" >Your Balance</p>
</div>
<div style={{paddingTop:'25px'}} className="lawyer-payment-subheading-btn-end">
<div className="system-ui-bold-text" style={{fontSize: "18px",padding: '8px 5px 0px 5px' }}>Widthdraw Balance:</div>
<button
className="yellow-button "
// checked={cardId === 1}
style={{display:'inline',marginRight: '10px'}}
onClick={this.handlePaypalPayment}
>
Paypal Account
</button>
<button
// checked={cardId === 2}
onClick={this.handleBankPayment}
className="yellow-button " style={{display:'inline'}}>
<img style={{marginRight:'10px'}}
src={require("../../assets/img/bank.png")} />
Bank Account
</button>
</div>
</div>
<div className='user-con-filter page-extras'>
{/* search bar and calender*/}
{/* table */}
</div>
<div className='pagination-dim'>
</div>
</div>
</div>
</div>
<div
style={{display: 'none'}}
>
<WidthdrawPayment
{...this.state}
{...this.props}
handlePaypalPayment={this.handlePaypalPayment}
handleBankPayment={this.handleBankPayment}
handleChange={ this.handlepaymenttypeChange}
/>
</div>
</div>
);
}
}
const wrappedFirmPaymentStats = withStyles(styles, { withTheme: true })(FirmPaymentStats);
const mapStateToProps = ({ instruction }) => ({
...instruction
});
export default connect(mapStateToProps, actions)(wrappedFirmPaymentStats)

How to get rid of this ? from the url

I'm making a react application and whenever I search for something(eg cat) on the homepage, the url changes to search/cat and the forward, backward button work normally & help me switch between the homepage and the cat search page ...but when i search for something again (eg rat) after(homepage->cat) so the url changes to search/rat? and now when i press the back button the url changes to search/rat and i'm on the same page then if i press back button again the url becomes search/cat but the page still has the results of the rat search and if i press back again ,the homepage appears..why is this happening?I think it's because of the ? that appears at the end of the url..Please help
after searching cat
after searching for rat
after pressing the back button
after pressing the back button
after pressing the back button
This is the code of the search bar
import React, { Component } from "react";
import "./styles/searchBar.scss";
import "font-awesome/css/font-awesome.min.css";
import { withRouter } from "react-router-dom";
import SearchForm from "./SearchForm";
import { connect } from "react-redux";
import { fetchRandomPhotos } from "../redux/actions/randomPhotoAction";
class SearchBar extends Component {
state = {
searchQuery: "",
};
componentDidMount() {
this.props.fetchRandomPhotos();
}
handleChange = (event) => {
this.setState({ searchQuery: event.target.value });
};
handleSubmit = (event) => {
//event.preventDefault();
this.props.history.push(`/search/${this.state.searchQuery}`);
};
handleProfile = () => {
this.props.history.push(`/public/${this.props.photo.user.username}`);
};
render() {
const { photo } = this.props;
return !photo ? (
<div className="search-bar-container">
<div className="search-bar-area">
<div className="about-foto-fab">
<h1>Foto-Fab</h1>
<p>The internet's source of freely-usable images.</p>
<p>Powered by creator everywhere</p>
</div>
<SearchForm
onSubmit={this.handleSubmit}
onChange={this.handleChange}
/>
</div>
</div>
) : (
<div
className="search-bar-container"
style={{ backgroundImage: `url("${photo.urls.full}")` }}
>
<div className="black-layer"></div>
<div className="search-bar-area">
<div className="about-foto-fab">
<h1>Foto-Fab</h1>
<p>The internet's source of freely-usable images.</p>
<p>Powered by creator everywhere</p>
</div>
<SearchForm
onSubmit={this.handleSubmit}
onChange={this.handleChange}
/>
</div>
<div className="picture-info">
<div className="photographer">
<p onClick={this.handleProfile}>
<strong>Photo</strong> by {""}
<strong>{photo.user.name}</strong>
</p>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
photo: state.randomPhotoState.photo,
};
};
export default connect(mapStateToProps, { fetchRandomPhotos })(
withRouter(SearchBar)
);
This is the App.js
import React from "react";
import Navbar from "./components/Navbar";
import { BrowserRouter, Switch, Route, Redirect } from "react-router-dom";
import Home from "./pages/Home";
import LoginPage from "./pages/LoginPage";
import ProfilePage from "./pages/ProfilePage";
import SearchPage from "./pages/SearchPage";
import PublicUserProfilePage from "./pages/publicUserProfilePage";
import MobileNavigation from "./components/MobileNavigation";
import AboutPage from "./pages/AboutPage";
function App() {
return (
<BrowserRouter>
<Navbar />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={LoginPage} />
<Route exact path="/profile" component={ProfilePage} />
<Route exact path="/search/:searchQuery" component={SearchPage} />
<Route exact path="/about" component={AboutPage} />
<Route
exact
path="/public/:username"
component={PublicUserProfilePage}
/>
<Redirect to="/" />
</Switch>
<MobileNavigation />
</BrowserRouter>
);
}
export default App;
search form component
import React, { Component } from "react";
export class SearchForm extends Component {
render() {
const { onSubmit, onChange } = this.props;
return (
<form className="search-form" onSubmit={onSubmit}>
<input
type="text"
placeholder="Search free high-resolution photos"
onChange={onChange}
/>
<button type="submit">
<i className="fa fa-search"></i>
</button>
</form>
);
}
}
export default SearchForm;
import React, { Component } from "react";
import "./styles/searchBar.scss";
import "font-awesome/css/font-awesome.min.css";
import { withRouter } from "react-router-dom";
import SearchForm from "./SearchForm";
import { connect } from "react-redux";
import { fetchRandomPhotos } from "../redux/actions/randomPhotoAction";
class SearchBar extends Component {
state = {
searchQuery: "",
};
componentDidMount() {
this.props.fetchRandomPhotos();
}
handleChange = (event) => {
this.setState({ searchQuery: event.target.value });
};
handleSubmit = (event) => {
event.preventDefault();
if (this.state.searchQuery) {
this.props.history.push(`/search/${this.state.searchQuery}`);
}
};
handleProfile = () => {
this.props.history.push(`/public/${this.props.photo.user.username}`);
};
render() {
const { photo } = this.props;
return !photo ? (
<div className="search-bar-container">
<div className="search-bar-area">
<div className="about-foto-fab">
<h1>Foto-Fab</h1>
<p>The internet's source of freely-usable images.</p>
<p>Powered by creator everywhere</p>
</div>
<SearchForm
onSubmit={this.handleSubmit}
onChange={this.handleChange}
/>
</div>
</div>
) : (
<div
className="search-bar-container"
style={{ backgroundImage: `url("${photo.urls.full}")` }}
>
<div className="black-layer"></div>
<div className="search-bar-area">
<div className="about-foto-fab">
<h1>Foto-Fab</h1>
<p>The internet's source of freely-usable images.</p>
<p>Powered by creator everywhere</p>
</div>
<SearchForm
onSubmit={this.handleSubmit}
onChange={this.handleChange}
/>
</div>
<div className="picture-info">
<div className="photographer">
<p onClick={this.handleProfile}>
<strong>Photo</strong> by {""}
<strong>{photo.user.name}</strong>
</p>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
photo: state.randomPhotoState.photo,
};
};
export default connect(mapStateToProps, { fetchRandomPhotos })(
withRouter(SearchBar)
);

Edit component inside Drawer component

I am using react-admin framework and I am trying to put the <Edit> component inside <Drawer> component. I need this in order to be able to save changes done in my JsonInput.
This is my custom component:
import React, { Component, Fragment } from 'react';
import { fetchUtils, CardActions, EditButton, Button, List, Datagrid, Edit } from 'react-admin';
import Drawer from '#material-ui/core/Drawer';
import JsonInput from 'react-json-view';
import EditIcon from '#material-ui/icons/Edit';
import IconKeyboardArrowRight from '#material-ui/icons/KeyboardArrowRight';
import { SimpleForm } from 'ra-ui-materialui/lib/form';
const divStyle = {
width: '400px',
margin: '1em'
};
export default class JsonEditButton extends React.Component {
constructor(props, context) {
super(props, context);
this.state = { showPanel: false };
}
handleClick = () => {
this.setState({ showPanel: true });
};
handleCloseClick = () => {
this.setState({ showPanel: false });
};
onChange = (value) => {
const { updated_src, name, namespace, new_value, existing_value } = value;
//this.onChange(updated_src);
}
render() {
const { showPanel } = this.state;
return (
<div>
<Button label="Upravit JSON" onClick={this.handleClick}>
<EditIcon />
</Button>
<Fragment>
<Drawer
anchor="right"
open={showPanel}
onClose={this.handleCloseClick}
>
<div>
<Button label="Zavřít" onClick={this.handleCloseClick}>
<IconKeyboardArrowRight />
</Button>
</div>
<div style={divStyle}>
{props => (
<Edit {...props}>
<SimpleForm>
{this.props.record && <JsonInput src={this.props.record} name={null} displayDataTypes={false} displayObjectSize={false} onEdit={this.onChange} onAdd={this.onChange} onDelete={this.onChange} />}
</SimpleForm>
</Edit>
)}
</div>
</Drawer>
</Fragment>
</div>
);
}
};
However this doesnt return any HTML.
Any idea how to solve this?
Thank you in advance.
Maybe this may help
<div style={divStyle}>
<Edit {...this.props}>
<SimpleForm>
{this.props.record && <JsonInput src={this.props.record} name={null} displayDataTypes={false} displayObjectSize={false} onEdit={this.onChange} onAdd={this.onChange} onDelete={this.onChange} />}
</SimpleForm>
</Edit>
</div>
the previous code where {props => ()} is actually a function or you could try this
<div style={divStyle}>
{props => (
return(
<Edit {...props}>
<SimpleForm>
{this.props.record && <JsonInput src={this.props.record} name={null} displayDataTypes={false} displayObjectSize={false} onEdit={this.onChange} onAdd={this.onChange} onDelete={this.onChange} />}
</SimpleForm>
</Edit>)
)}
</div>

how to pass props from parent to child component

I have a list of comments on soccer champions, and am trying to display comments of each soccer champion separately. I'm trying to order by id in firebase, but don't know how I can pass id from the champion component to the component where I display all the comments. It's just giving me undefined for some reason. Any help is greatly appreciated!
champ.js
import React, { Component } from "react";
import { ChampsRef, timeRef } from "./reference";
import { getsinglechamp } from "../actions/champs";
import { connect } from "react-redux"; // this is not being used. oh isee so like this?
import { Redirect, Link } from "react-router-dom";
import { Container, Row, Col } from "reactstrap";
import { Upvote } from "react-upvote";
import Form from "./Form";
import { Icon } from "react-icons-kit";
import Specials from "./specials";
import app from "../config/dev";
import { chevronDown } from "react-icons-kit/fa/chevronDown";
import { chevronUp } from "react-icons-kit/fa/chevronUp";
class OneChamp extends Component {
state = {
name: "",
weak: [],
img: "",
authenticated: false,
currentUser: null,
email: ""
};
componentDidMount() {
app.auth().onAuthStateChanged(user => {
if (user) {
this.setState({
currentUser: user,
email: user.email,
authenticated: true
});
} else {
this.setState({
currentUser: null,
authenticated: false
});
}
});
}
componentWillMount() {
const { dispatch, match } = this.props;
dispatch(getsinglechamp(match.params.id));
console.log(this.props);
}
render() {
console.log(this.props.champ);
const { dispatch, loading } = this.props;
const authenticated = this.state.authenticated;
console.log("change", this.props);
console.log("c", this.props.champ.img);
console.log("", this.props.champ.stats);
const champ = this.props.champ.stats;
let content = null;
if (loading) {
content = <p>Loading...</p>;
} else {
content = (
<div id="f">
<div className="ChampionHeader_row_ArTlM">
<div
style={{
paddingRight: "0.75rem",
paddingLeft: "0.75rem",
flexGrow: 1
}}
>
<div style={{ display: "flex", marginBottom: "1.5rem" }}>
<div style={{ flexShrink: 0, marginRight: "1rem" }}>
<div className="IconChampion_component_2qg6y IconChampion_lg_2QLBf">
<img
className="v-lazy-image v-lazy-image-loaded IconChampion_img_3U2qE"
src={this.props.champ.img}
height="80px"
/>
</div>
</div>
</div>
</div>
</div>
<div className="timeline-panel">
<div className="timeline-heading">
{" "}
<h4>{this.props.champ.name}</h4>
</div>
<ul>
{Object.keys(champ).map((item, i) => (
<div className="card">
<li className="travelcompany-input" key={i}>
<div> {champ[item]}</div>
</li>
</div>
))}
</ul>
<br />
<div className="w3-container">
// place i want to pass id <Comments id={this.props.champ.id} />
<h2>Weak To</h2> <br />
<ul className="w3-ul w3-card-4">
<li className="w3-bar">
<img
src={this.props.champ.img2}
className="w3-bar-item w3-circle w3-hide-small"
style={{ width: 145 }}
/>
<div className="w3-bar-item">
<span className="w3-large">{this.props.champ.weak}</span>
<br />
<span id="item"> Mid </span>
<div className="col-sm-5">
<span className="label label-primary">
{this.props.champ.win}
</span>
</div>
</div>
</li>
<li className="w3-bar">
<img
src={this.props.champ.img3}
className="w3-bar-item w3-circle w3-hide-small"
style={{ width: 145 }}
/>
<div className="w3-bar-item">
<Link to={`/Matchup/${this.props.champ.id}`}>
{" "}
<span className="w3-large">{this.props.champ.weak3}</span>
<br />{" "}
</Link>
<span id="item"> Mid </span>
<span className="label label-primary">
{this.props.champ.win}
</span>
</div>
</li>
</ul>
</div>
</div>
<div />
{authenticated ? (
<div className="nav-item">
<Form id={this.props.champ.id} />
</div>
) : (
<div className="nav-item">
    
<Link to="/login" className="nav-link2">
{" "}
Login to post
</Link>
</div>
)}
</div>
);
}
return <div>{content}</div>;
}
}
const mapStateToProps = state => {
console.log("champs", state.champs);
console.log(state.loading);
return {
champ: state.champs.champ,
loading: state.loading
};
};
export default connect(
mapStateToProps,
null
)(OneChamp);
comments.js
import React, { Component } from "react";
import axios from "axios";
import app from "../config/dev";
import { Link } from "react-router-dom";
import { ChampsRef, CommentsRef, timeRef } from "./reference";
import { connect } from "react-redux";
import { getsinglechamp } from "../actions/champs";
class Comments extends Component {
state = {
comments: [],
champ_id: "",
loading: true,
email: ""
};
componentWillMount() {
const champ_id = this.props.champ.id;
console.log("id", this.props.champ);
CommentsRef.orderByChild("champ_id")
.equalTo(`${champ_id}`)
.on("value", snap => {
const tasks = [];
let comments = [];
snap.forEach(child => {
comments.push({ ...child.val(), key: child.key });
});
this.setState({ comments: comments, Loading: false });
});
}
render() {
const { dispatch, loading } = this.props;
const { comments, ChampsLoading } = this.state;
const orderedchamps = comments;
let commentList;
if (ChampsLoading) {
commentList = <div className="TaskList-empty">Loading...</div>;
} else if (comments.length) {
commentList = (
<ul className="TaskList">
{comments.map(comment => (
<div>{comment.text}</div>
))}
</ul>
);
}
return (
<div>
<h1> Popular Cham</h1>
<p> {commentList} </p>
</div>
);
}
}
const mapStateToProps = state => {
console.log("champs", state.champs);
console.log(state.loading);
return {
champ: state.champs.champ,
loading: state.loading
};
};
export default connect(
mapStateToProps,
null
)(Comments);

Resources