Pass props to child component from parent component dynamically - reactjs

I have a child component StepperNotification which gets an input from user and returns it as prop to its child component in following way.
const styles = {
transparentBar: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
}
};
const useStyles = makeStyles((theme: Theme) =>
createStyles({
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
},
}),
);
function getSteps() {
return ['Create', 'Audience', 'Timing'];
}
function getStepContent(step, $this) {
switch (step) {
case 0:
return (
<div className="row">
<CardBox styleName="col-lg-12"
heading="">
<form className="row" noValidate autoComplete="off" style={{"flex-wrap":"no-wrap", "flex-direction": "column" }}>
<div className="col-md-12 col-12">
<TextField
id="campaign_name"
label="Campaign Name"
value={$this.state.name}
onChange={$this.handleChange('name')}
margin="normal"
fullWidth
/>
</div>
</form>
</CardBox>
</div>
);
default:
return 'Unknown step';
}
}
class NotificationStepper extends React.Component {
state = {
activeStep: 0,
name: '',
};
handleChange = name => event => {
this.setState({
[name]: event.target.value,
});
this.props.titlechange(event.target.value);
};
handleNext = () => {
this.setState({
activeStep: this.state.activeStep + 1,
});
};
handleBack = () => {
this.setState({
activeStep: this.state.activeStep - 1,
});
};
handleReset = () => {
this.setState({
activeStep: 0,
});
};
render() {
const steps = getSteps();
const {activeStep} = this.state;
return (
<div className="col-xl-12 col-lg-12 col-md-7 col-12">
<Stepper className="MuiPaper-root-custom" activeStep={activeStep} orientation="vertical">
{steps.map((label, index) => {
return (
<Step key={label}>
<StepLabel>{label}</StepLabel>
<StepContent className="pb-3">
<Typography>{getStepContent(index, this)}</Typography>
<div className="mt-2">
<div>
<Button
disabled={activeStep === 0}
onClick={this.handleBack}
className="jr-btn"
>
Back
</Button>
<Button
variant="contained"
color="primary"
onClick={this.handleNext}
className="jr-btn"
>
{activeStep === steps.length - 1 ? 'Finish' : 'Next'}
</Button>
</div>
</div>
</StepContent>
</Step>
);
})}
</Stepper>
{activeStep === steps.length && (
<Paper square elevation={0} className="p-2">
<Typography>All steps completed - you"re finished</Typography>
<Button onClick={this.handleReset} className="jr-btn">
Reset
</Button>
</Paper>
)}
</div>
);
}
}
export default NotificationStepper;
In my parent component i am getting this prop value and passing it to another child component Tabcomponent in following way
ParentCompoennt.js
const SendNotification = ({match}) => {
let titlename = '';
let message = '';
function handleTitle(title_) {
console.log('in here');
console.log(title_);
titlename = title_;
}
return (
<div className="dashboard animated slideInUpTiny animation-duration-3">
<ContainerHeader match={match} title={<IntlMessages id="sidebar.notification"/>}/>
<div className="row" style={{'flex-wrap': 'no wrap', "flex-direction": 'row'}}>
<div className="col-xl-7 col-lg-7 col-md-7 col-7">
<NotificationStepper titlechange={handleTitle} />
<div className='flex-class' style={{'width': '100%'}}>
<Button color="primary" style={{"align-self": "flex-end", "border" : "1px solid", "margin-left": "10px", "margin-bottom": "40px"}} size="small" className="col-md-2 col-2">Fetch</Button>
<Button color="primary" style={{"align-self": "flex-end", "border" : "1px solid", "margin-left": "10px", "margin-bottom": "40px"}} size="small" className="col-md-2 col-2" color="primary">Discard</Button>
</div>
</div>
<div className="col-xl-5 col-lg-5 col-md-5 col-5" style={{"padding-top": "20px"}}>
<span style={{"margin-left" : "20px", "font-weight": "bold"}}>Preview</span>
<TabComponent {...{[title]:titlename}} message={message} />
</div>
</div>
</div>
);
};
export default SendNotification;
and in TabComponent i am getting this prop value and using it component in following way
TabContainer.propTypes = {
children: PropTypes.node.isRequired,
dir: PropTypes.string.isRequired,
};
class TabComponent extends Component {
state = {
value: 0,
};
render() {
const {theme} = this.props;
const title = this.props.title;
return (
<div className="col-xl-12 col-lg-12 col-md-12 col-12" style={{"margin-top": "15px"}}>
<NotifCard key={0} data={{'name': title, 'company': 'sayge.ai', 'image': require("assets/images/bell.png"), 'description': this.props.message}} styleName="card shadow "/>
</div>
);
}
}
TabComponent.propTypes = {
theme: PropTypes.object.isRequired,
};
export default withStyles(null, {withTheme: true})(TabComponent);
StepperNotification is working fine and props are being updated in parent. i have checked this by printing the updated values in console, but the props in TabComponent are not being updated. What am i doing wrong here? any help is appreciated.

Probaly this is your issue
<TabComponent {...{[title]:titlename}} message={message} />` this could be just
title is undefined and you are sending props[undefined]=titlename
Just do this
<TabComponent title={titlename} message={message} />`
And if SendNotification is react fuction component useState for keeping track of current titlename. If it still doesn't work after first fix this second will be another source of your problems.

Related

Using working fileupload code inside a form with formki api

I have my form using formik. and I want to use the file upload logic in my form which is shown in the sandbox here.
Quick Description of what's in sandbox:
User uploads a file, and based on the # of files, they will see a datatable rows and answer some questions by editing that row using edit button and then saving their response using checkmark button.
Right now, when a user hits Save button, it prints in the console log the values of what user has selected as an array of object.
I don't want to have this additional Save button in my form and want to send these values when a user hits the Submit button of my form along with other values.
I was playing with my sandbox code by putting it at the location in my form where {uploadDocumentSection} is mentioned in my code below. However,
I'm unable to get the data from the dynamicData variable which is storing the responses from the user.
Is it possible to achieve what I'm looking for?
return (
<div>
<style jsx>{`
text-align: center;
padding: 5px;
#formEdwDiv {
padding: 20px;
}
`}
</style>
<div id="formEdwDiv">
<Growl ref={growl}/>
<Form className="form-column-3">
<div className="datarequest-form">
<div className="form-field field-full-width">
<label className="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-animated custom-label">Title <span className="astrick">*</span></label>
<CustomTextField name="title" type="text"/>
</div>
<div className="form-field field-full-width">
<label className="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-animated custom-label">Description <span className="astrick">*</span></label>
<CustomTextAreaField name = "description" type ="text" />
{touched.description && errors.description && <Message severity="error" text={errors.description}/>}
</div>
</div>
{uploadDocumentSection}
<div className="btn-group-right">
<Button size="large" variant="contained" color="primary" id="edw-submit"
type="submit">Submit</Button>
<Button size="large" variant="contained" color="primary" onClick={handleReset}
style={{marginLeft: '5px'}} type="button">Reset</Button>
<Button size="large" variant="contained" color="primary" onClick={props.onCancel}
style={{marginLeft: '5px'}} type="button">Cancel</Button>
</div>
</Form>
</div>
</div>
)
};
export const RequestEnhancedForm = withFormik(
{
mapPropsToValues: props => {
return {
requestId: props.dataRequest && props.dataRequest.requestId || '',
title: props.dataRequest && props.dataRequest.title || '',
}
},
validationSchema:validationSchema,
handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
console.log("submit data request form....")
props.handleSubmit(values)
setSubmitting(false)
},
setFieldValue(field, value, shouldVal) {
console.log('In setFieldValue')
},
displayName: 'Data Request Form',
})(DataRequestForm)
Here is my code from Codesandbox if needed:
const answers = [
{ label: "Yes", value: "YES" },
{ label: "No", value: "NO" }
];
export const FileUploadDemo = () => {
const toast = useRef(null);
const fileUploadRef = useRef(null);
const [dynamicData, setDynamicData] = useState([]);
const getAnswerLabel = (answer) => {
switch (answer) {
case "YES":
return "Yes";
case "NO":
return "No";
default:
return "NA";
}
};
const onRowEditComplete1 = (e) => {
console.log("Testing e");
console.log(e);
let _dynamicData = [...dynamicData];
let { newData, index } = e;
_dynamicData[index] = newData;
setDynamicData(_dynamicData);
};
const textEditor = (options) => {
return (
<InputText
type="text"
value={options.value}
onChange={(e) => options.editorCallback(e.target.value)}
/>
);
};
const answerEditor = (options) => {
return (
<Dropdown
value={options.value}
options={answers}
optionLabel="label"
optionValue="value"
onChange={(e) => options.editorCallback(e.value)}
placeholder="Select an answer"
itemTemplate={(option) => {
return <span className={`product-badge`}>{option.label}</span>;
}}
/>
);
};
const answer1BodyTemplate = (rowData) => {
return getAnswerLabel(rowData.answer1);
};
const answer2BodyTemplate = (rowData) => {
return getAnswerLabel(rowData.answer2);
};
const onUpload = (e) => {
// toast.current.show({
// severity: "info",
// summary: "Success",
// detail: "File Uploaded"
// });
console.log("File Upload event e");
console.log(e);
const newData = e.files.map((file) => ({
filename: file.name,
answer1: null,
answer2: null,
description: ""
}));
setDynamicData([...dynamicData, ...newData]);
};
return (
<div>
<Tooltip target=".custom-choose-btn" content="Choose" position="bottom" />
<Tooltip target=".custom-upload-btn" content="Upload" position="bottom" />
<Tooltip target=".custom-cancel-btn" content="Clear" position="bottom" />
<div className="card">
<h5>Advanced</h5>
<FileUpload
name="demo[]"
url="https://primefaces.org/primereact/showcase/upload.php"
onUpload={onUpload}
customUpload
uploadHandler={onUpload}
multiple
accept="image/*"
maxFileSize={1000000}
emptyTemplate={
<p className="m-0">Drag and drop files to here to upload.</p>
}
/>
</div>
<div className="datatable-editing-demo">
{/* <Toast ref={toast} /> */}
<div className="card p-fluid">
<h5>Row Editing</h5>
<DataTable
value={dynamicData}
editMode="row"
dataKey="id"
onRowEditComplete={onRowEditComplete1}
responsiveLayout="scroll"
>
<Column
field="filename"
header="Filename"
editor={(options) => textEditor(options)}
style={{ width: "20%" }}
></Column>
<Column
field="answer1"
header="Q1"
body={answer1BodyTemplate}
editor={(options) => answerEditor(options)}
style={{ width: "20%" }}
></Column>
<Column
field="answer2"
header="Q2"
body={answer2BodyTemplate}
editor={(options) => answerEditor(options)}
style={{ width: "20%" }}
></Column>
<Column
field="description"
header="Description"
editor={(options) => textEditor(options)}
style={{ width: "20%" }}
></Column>
<Column
rowEditor
headerStyle={{ width: "10%", minWidth: "8rem" }}
bodyStyle={{ textAlign: "center" }}
></Column>
</DataTable>
</div>
</div>
<Button label="Save" onClick={() => console.log(dynamicData)} />
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<FileUploadDemo />, rootElement);

Passing value of component in separate jsx file's value to event on Full-Calendar

I am new to React. I am trying to pass the value of a select box imported from a separate .jsx file to an event for full-calendar. I can't find anything on this or figure out how to do it for the life of me. This is my component for the select box in a separate file.
import React from 'react'
export const Dropdown = (props) => (
<div className="form-group">
<select
className="form-control"
name="partner"
onChange={props.onChange}
>
<option defaultValue>Select Partner</option>
{props.options.map((item, index) => (
<option key={index} value={item.value}>
{item.label}
</option>
))}
</select>
</div>
)
export default class DropdownList extends React.Component {
constructor() {
super()
this.state = {
list: [],
chosenValue: '',
}
}
componentDidMount() {
fetch('/calendar/users')
.then((response) => response.json())
.then((item) => this.setState({ list: item }))
}
onDropdownChange = (e) => {
this.setState({ chosenValue: e.target.value })
}
render() {
return (
<div className="form-group">
<Dropdown
name="partner"
id="partner"
options={this.state.list}
onDropdownChange={this.onDropdownChange}
/>
</div>
)
}
}
This is my modal that contains the form to pass through as an event to full-calendar
import React, {useState} from "react";
import Modal from "react-modal";
import DateTimePicker from "react-datetime-picker";
import 'bootstrap-icons/font/bootstrap-icons.css'
import DropdownList from "./SelectBox";
export default function ({ isOpen, onClose, onEventAdded }) {
const [title, setTitle] = useState("");
const [start, setStart] = useState(new Date());
const [end, setEnd] = useState(new Date());
const [selectValue] = useState(DropdownList);
const onSubmit = (event) => {
event.preventDefault();
onEventAdded({
title,
start,
partner: selectValue,
end
});
onClose()
};
return (
<Modal isOpen={isOpen}
onClose={onClose}
style={{
overlay: {
backgroundColor: 'rgba(0, 0, 0, 0.5)'
},
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
transform: 'translate(-50%, -50%)',
border: '1px solid #ccc',
background: '#fff',
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
borderRadius: '4px',
outline: 'none',
padding: '20px',
maxWidth: '1200px',
minHeight: '80%',
textAlign: 'center'
}
}}
>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch#4.5.2/dist/lux/bootstrap.min.css" />
<form onSubmit={onSubmit}>
<div className='form-group'>
<input className='form-control' placeholder="Title" value={title} onChange={e => setTitle(e.target.value)} />
</div>
<DropdownList />
<div className='form-group'>
<DateTimePicker name='start' value={start} onChange={date => setStart(date)} />
</div>
<div className='form-group'>
<DateTimePicker name='end' value={end} onChange={date =>setEnd(date)} />
</div>
<button className="btn btn-primary btn-block" type="submit">Add Event</button>
<button className="btn btn-danger btn-block" onClick={onClose}>Cancel</button>
</form>
</Modal>
)
}
I have tried DropdownList.value, redoing the onDropdownChange(e) function in the modal jsx file to no avail. I'm sure this is really simple and I'm getting a headache so thank you for your kindness ahead of time. I'm currently trying to use props but it's all coming up undefined.
Edit: tried to add to component in the modal file
const [partner, setPartner] = useState();
<DropdownList
ref={partnerRef}
onDropdownChange={e => setPartner(this.chosenValue = e.target.value)}
/>

Menu items are not clickable after rendering Google Maps container

My semantic-ui-react Menu component is acting strange when I add my google maps component to be rendered. Before I added my MapContainer, the FilterSection was working pretty fine. But after I render the MapContainer my sections in my Menu are no longer clickable nor do they react to my mouse hover. What should I do?
Snippet of render:
return (
<div>
<Navbar/>
<FilterSection/>
<ChatWidget/>
<div className="map-and-cards">
<MapContainer/> // This line causes the problem
<div style={containerStyle} className="cards-container">
<div class="card-columns" style={{gridTemplateColumns: '350px 350px', display: 'grid', rowGap: '50px', columnGap: '18px'}}>
<Cards listingData={listingData}/>
</div>
</div>
</div>
</div>
)
and my MapContainer.js:
import React from 'react';
import { Map, GoogleApiWrapper } from 'google-maps-react';
const style = {
position: 'relative',
top: '65px',
width: '47.5%', // 47.5
height: '85%',
};
const defaultCenter = {
lat: 41.04137, lng: 28.979530
}
export class MapContainer extends React.Component<MapProps> {
render() {
return (
<Map
style = {style}
google={this.props.google}
centerAroundCurrentLocation={true}
zoom={12}
initialCenter={defaultCenter}
/>
);
}
}
export default GoogleApiWrapper({
apiKey: (0)
})(MapContainer)
FilterSection.js:
import React, { Component } from "react";
import { Menu, Dropdown, Input, Button } from "semantic-ui-react";
import 'semantic-ui-css/semantic.min.css'
export class Price extends Component {
state = { isOpen: false };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div style={{float: 'left'}}>
<Menu secondary >
<Menu.Item>
<Dropdown
text={"Price"}
className="item"
onClick={this.toggleOpen}
open={this.state.isOpen}
>
<Dropdown.Menu onClick={this.preventClosing}>
<Dropdown.Header icon="money" content={" Price Range"} />
<Dropdown.Divider />
<form
style = {{margin: '10px'}}
name="id"
type="number"
max={900}
action={<Button onClick={this.toggleOpen} content={"Send"} />}
>
<Input style={{zoom: '0.9'}} placeholder="min"/> — <Input style={{zoom: '0.9'}} placeholder="max"/>
</form>
</Dropdown.Menu>
</Dropdown>
</Menu.Item>
</Menu>
</div>
);
}
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
preventClosing = e => e.stopPropagation();
}
export class BedsAndBaths extends Component {
state = { isOpen: false };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div style={{float: 'left'}}>
<Menu secondary>
<Menu.Item>
<Dropdown
text={"Bedrooms & Livingrooms"}
className="item"
onClick={this.toggleOpen}
open={this.state.isOpen}
>
<Dropdown.Menu onClick={this.preventClosing}>
<form
style = {{margin: '10px'}}
name="id"
type="number"
max={900}
action={<Button onClick={this.toggleOpen} content={"Send"} />}
>
<Input style={{zoom: '0.9'}} placeholder="3"/> + <Input style={{zoom: '0.9'}} placeholder="1"/>
</form>
</Dropdown.Menu>
</Dropdown>
</Menu.Item>
</Menu>
</div>
);
}
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
preventClosing = e => e.stopPropagation();
}
export class More extends Component {
state = { isOpen: false };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div style={{float: 'left'}}>
<Menu secondary>
<Menu.Item>
<Dropdown
text={"More"}
className="item"
onClick={this.toggleOpen}
open={this.state.isOpen}
>
<Dropdown.Menu onClick={this.preventClosing}>
<Dropdown.Header icon="money" content={" Price Range"} />
<Dropdown.Divider />
<form
style = {{margin: '10px'}}
name="id"
type="number"
max={900}
action={<Button onClick={this.toggleOpen} content={"Send"} />}
>
<Input style={{zoom: '0.9'}} placeholder="min"/> — <Input style={{zoom: '0.9'}} placeholder="max"/>
</form>
</Dropdown.Menu>
</Dropdown>
</Menu.Item>
</Menu>
</div>
);
}
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
preventClosing = e => e.stopPropagation();
}
export class Alert extends Component {
state = { isOpen: false };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div style={{float: 'left', position: 'relative', top: '11.5px', left: '15px', zoom: '0.9'}}>
<Menu secondary >
<button class="ui button ">
Create Alert
</button>
</Menu>
</div>
);
}
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
preventClosing = e => e.stopPropagation();
}
export class Search extends Component {
state = { isOpen: false };
handleItemClick = (e, { name }) => this.setState({ activeItem: name });
render() {
const { activeItem } = this.state;
return (
<div style={{float: 'left', position: 'relative', top: '12px', right: '50px', zoom: '0.9'}}>
<Menu secondary >
<div style={{float: 'left', position: 'relative', right: '10px'}} class="ui input focus">
<input type="text" placeholder="Enter an adress, neigborhood, city, or ZIP code
" size="45"/>
</div>
<button class="ui button ">
Search
</button>
</Menu>
</div>
);
}
toggleOpen = () => this.setState({ isOpen: !this.state.isOpen });
preventClosing = e => e.stopPropagation();
}
export default function FilterSection(){
return (
<div style={{position: 'relative', left: '75px', bottom: '1px'}}><Search/><div style={{position: 'relative', right: '30px'}}><More/><BedsAndBaths/><Price/><Alert/></div></div>
)
}
As I said, only the MapContainer component is triggering the deactivation of the menu.
You can see the actual page at royaremlak.com/search

Update the input value from one component in an other on runtime

I have a NotificationStepper Component which gets inputs from user, I need to update this input value in run time in another component named TabComponent. Both of the components are child components of SendNotification Component. How can i achieve that in reactjs.
EDIT
NotificationStepper.js
const styles = {
transparentBar: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
}
};
const useStyles = makeStyles((theme: Theme) =>
createStyles({
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
},
}),
);
function getSteps() {
return ['Create', 'Audience', 'Timing'];
}
function getStepContent(step, $this) {
switch (step) {
case 0:
return (
<div className="row">
<CardBox styleName="col-lg-12"
heading="">
<form className="row" noValidate autoComplete="off" style={{"flex-wrap":"no-wrap", "flex-direction": "column" }}>
<div className="col-md-12 col-12">
<TextField
id="campaign_name"
label="Campaign Name"
value={$this.state.name}
onChange={$this.handleChange('name')}
margin="normal"
fullWidth
/>
</div>
</form>
</CardBox>
</div>
);
default:
return 'Unknown step';
}
}
class NotificationStepper extends React.Component {
state = {
activeStep: 0,
name: '',
};
handleChange = name => event => {
this.setState({
[name]: event.target.value,
});
};
handleNext = () => {
this.setState({
activeStep: this.state.activeStep + 1,
});
};
handleBack = () => {
this.setState({
activeStep: this.state.activeStep - 1,
});
};
handleReset = () => {
this.setState({
activeStep: 0,
});
};
render() {
const steps = getSteps();
const {activeStep} = this.state;
return (
<div className="col-xl-12 col-lg-12 col-md-7 col-12">
<Stepper className="MuiPaper-root-custom" activeStep={activeStep} orientation="vertical">
{steps.map((label, index) => {
return (
<Step key={label}>
<StepLabel>{label}</StepLabel>
<StepContent className="pb-3">
<Typography>{getStepContent(index, this)}</Typography>
<div className="mt-2">
<div>
<Button
disabled={activeStep === 0}
onClick={this.handleBack}
className="jr-btn"
>
Back
</Button>
<Button
variant="contained"
color="primary"
onClick={this.handleNext}
className="jr-btn"
>
{activeStep === steps.length - 1 ? 'Finish' : 'Next'}
</Button>
</div>
</div>
</StepContent>
</Step>
);
})}
</Stepper>
{activeStep === steps.length && (
<Paper square elevation={0} className="p-2">
<Typography>All steps completed - you"re finished</Typography>
<Button onClick={this.handleReset} className="jr-btn">
Reset
</Button>
</Paper>
)}
</div>
);
}
}
export default NotificationStepper;
TabComponent.js
TabContainer.propTypes = {
children: PropTypes.node.isRequired,
dir: PropTypes.string.isRequired,
};
class TabComponent extends Component {
state = {
value: 0,
};
render() {
const {theme} = this.props;
return (
<div className="col-xl-12 col-lg-12 col-md-12 col-12" style={{"margin-top": "15px"}}>
<NotifCard key={0} data={{'name': 'Title of Notification', 'company': 'sayge.ai', 'image': require("assets/images/chrome.png"), 'description': 'Notification Message here'}} styleName="card shadow "/>
</div>
);
}
}
TabComponent.propTypes = {
theme: PropTypes.object.isRequired,
};
export default withStyles(null, {withTheme: true})(TabComponent);
and this is my SendNotification.js
const SendNotification = ({match}) => {
return (
<div className="dashboard animated slideInUpTiny animation-duration-3">
<ContainerHeader match={match} title={<IntlMessages id="sidebar.notification"/>}/>
<div className="row" style={{'flex-wrap': 'no wrap', "flex-direction": 'row'}}>
<div className="col-xl-7 col-lg-7 col-md-7 col-7">
<NotificationStepper/>
<div className='flex-class' style={{'width': '100%'}}>
<Button color="primary" style={{"align-self": "flex-end", "border" : "1px solid", "margin-left": "10px", "margin-bottom": "40px"}} size="small" className="col-md-2 col-2">Fetch</Button>
<Button color="primary" style={{"align-self": "flex-end", "border" : "1px solid", "margin-left": "10px", "margin-bottom": "40px"}} size="small" className="col-md-2 col-2" color="primary">Discard</Button>
</div>
</div>
<div className="col-xl-5 col-lg-5 col-md-5 col-5" style={{"padding-top": "20px"}}>
<span style={{"margin-left" : "20px", "font-weight": "bold"}}>Preview</span>
<TabComponent />
</div>
</div>
</div>
);
};
export default SendNotification;
i need to get the name value from NotificationStepper and Update it in pass it to in TabComponent.
There are plenty of tutorials about that. For instance, this.
import React, { Component, createRef } from "react";
class CustomTextInput extends Component {
textInput = createRef();
focusTextInput = () => this.textInput.current.focus();
render() {
return (
<>
<input type="text" ref={this.textInput} />
<button onClick={this.focusTextInput}>Focus the text input</button>
</>
);
}
}
import React, { useRef } from "react";
const CustomTextInput = () => {
const textInput = useRef();
focusTextInput = () => textInput.current.focus();
return (
<>
<input type="text" ref={textInput} />
<button onClick={focusTextInput}>Focus the text input</button>
</>
);
}

Button/dropdown button disabled by default without specifying disabled

I am trying to add a dropdown button in my react project and its rendering as disabled by default. why is this happening ?
The first dropdown is working fine, i called the same dropdown in the navbar after this one and it renders as disabled. I tried other things as well, like adding a button also would not work for me.
The navbar is diplayed when i get a response from the backend and a different component is rendered (ResultTable)
import React from "react";
import ResultTable from "./ResultTable";
...
import DropdownButton from "react-bootstrap/DropdownButton";
import Dropdown from "react-bootstrap/Dropdown";
class MainContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
//more state values
threshold: 0.75
};
this.thresholdChange = this.thresholdChange.bind(this);
}
thresholdChange(input) {
this.setState({
threshold: input
});
}
toProperCase = function (txt) {
return txt.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
};
render() {
const { responseData } = this.state;
return (
<div className="container-flex container-without-scroll wrapper"
style={{
backgroundImage: `url(${bg})`,
width: "100%",
height: "100vh",
backgroundSize: "cover",
backgroundRepeat: "no-repeat",
overFlow:'hidden'
}}
>
<div
className={`container-fluid `}>
{this.state.displayTable ? (
<Navbar
style={{
position: "fixed",
left: "50%",
top: "95%",
transform: "translate(-50%, -90%)",
backgroundColor: 'black'
}}
sticky="bottom"
>
<br />
<Navbar.Collapse className="justify-content-end">
<Button
variant="primary"
disabled={
this.props.initialTransaction &&
this.props.initialTransaction.version == 0 &&
this.props.initialTransaction
? true
: false
}
size="sm"
style={{ color: "#FFF" }}
onClick={this.undoAction}
>
<span className=" fa fa-undo "></span>
Undo
</Button>
<Button
variant="primary"
size="sm"
style={{ color: "#FFF" }}
disabled={
(this.props.initialTransaction &&
this.props.initialTransaction.version) <
(this.props.currentVersion &&
this.props.currentVersion.version)
? false
: true
}
onClick={this.redoAction}
>
<span className=" fa fa-repeat "></span>
Redo
</Button>
<Button
variant="success"
size="sm"
style={{ color: "#FFF" }}
disabled={
this.props.initialTransaction &&
this.props.initialTransaction.version == 0
? true
: false
}
onClick={() =>
this.exportExcel(this.props.initialTransaction)
}
>
<span className=" fa fa-download "></span>
Export
</Button>
<DropdownButton
size="md"
title={this.state.threshold}
>
{this.state.thresholdValues.map(eachValue => {
return (
<Dropdown.Item
key = {Math.random()}
onClick={() => this.thresholdChange(eachValue)}
as="button"
>
{eachValue}
</Dropdown.Item>
);
})}
</DropdownButton>
</Navbar.Collapse>
<br/>
</Navbar>
) : null}
{this.state.displayTable ? null : (
<div
className="col-md-4 col-md-offset-4"
style={{
position: "absolute",
left: "50%",
top: "50%",
transform: "translate(-50%, -50%)",
backgroundColor: 'rgba(14, 13, 13, 0.74)'
}}
>
<br />
<div className="row">
<div className="input-group col-md-9">
<div className="input-group-prepend">
<span
style={{ cursor: 'pointer' }}
onClick={this.onFormSubmit}
className="input-group-text"
id="inputGroupFileAddon01"
>
{" "}
Upload{" "}
</span>
</div>
<div className="custom-file">
<input
type="file"
className="custom-file-input"
id="inputGroupFile01"
onChange={this.onChange}
aria-describedby="inputGroupFileAddon01"
/>
<label
className="custom-file-label"
htmlFor="inputGroupFile01"
>
{this.props.active && this.props.active.filename}
</label>
</div>
</div>
<div className="col-md-3">
<DropdownButton
size="md"
id="dropdown-item-button"
title={this.state.threshold}
>
{this.state.thresholdValues.map(eachValue => {
return (
<Dropdown.Item
onClick={() => this.thresholdChange(eachValue)}
as="button"
>
{eachValue}
</Dropdown.Item>
);
})}
</DropdownButton>
</div>
</div>
<br />
</div>
)}
<div >
{this.state.displayTable ? (
<div className = "container-flex" style =
{{overflowY:'scroll', maxHeight:'80vh'}}>
<ResultTable
data={responseData}
afterMerge={params => {
this.afterMerge(params);
}}
/>
</div>
) : null}
</div>
</div>
</div>
);
}
}
// Maps state from store to props
const mapStateToProps = (state, ownProps) => {
return {
};
};
// Maps actions to props
const mapDispatchToProps = dispatch => {
return {
};
};
// Use connect to put them together
export default connect(
mapStateToProps,
mapDispatchToProps
)(MainContainer);

Resources