const SimpleChoiceItem = (props: Props) => {
const { content, isSelected, onChange, onMove, onDelete, is_default } = props;
const [isEdit, setIsEdit] = React.useState<boolean>(false);
React.useEffect(() => {
if (!isSelected) {
setIsEdit(false)
}
}, [isSelected])
return <div style={{ margin: '17px 0' }}>
{
isEdit ? <div style={{ display: 'flex', justifyContent: 'space-between', }} onBlur={() => {
console.log('====onBlur===')
setIsEdit(false)
}}>
<div style={{ flex: 1 }}>
<Input value={content} onChange={e => onChange(e.target.value)} />
</div>
<div>
<Checkbox value={is_default} onChange={e => {
// When I click this element, I want to console the below words, But console the onBlur
console.log('===Check box === onChange==')
}}>默认</Checkbox>
<ArrowUpOutlined style={{ marginLeft: '20px', cursor: 'pointer' }} onMouseDown={() => onMove('up')} />
<ArrowDownOutlined style={{ marginLeft: '20px', cursor: 'pointer' }} onMouseDown={() => onMove('down')} />
<CloseOutlined style={{ marginLeft: '20px', cursor: 'pointer' }} onMouseDown={() => onDelete()} />
</div>
</div> : <div onClick={() => setIsEdit(true)}>{content}</div>
}
</div>
}
<CheckBox /> is Antd Component https://ant.design/components/checkbox-cn/
I want to click this check box, But console the onBlur and isEdit = false
Try to prevent default and stop propagation on checkbox to stop event triggering the other elements:
<Checkbox value={is_default} onChange={e => {
e.preventDefault();
e.stopPropagation();
console.log('===Check box === onChange==')
}}>默认</Checkbox>
Related
Quantity component is my child class and Mainpart component is my parent class.i want to use my (count) in my parent class.but i dont know how to pass that data.sorry my english is not good.i think you will get the idea.
const MainPart = () => {
const submit = (event) => {
debugger;
event.preventDefault();
}
return (
<div>
<form onSubmit={submit}>
<Container>
<Row>
<Col sm={4}>
<Picture image='../images/test.jpg' alt='tent' />
</Col>
<Col sm={8}>
<Title title='4 Person tent' itemNo='Item No. MA000001' />
<Currency mark='$' price='150.00' />
<Quantity />
<div style={{ marginTop: '5%', textAlign: 'center' }}>
<input type='submit' value='ADD TO CART' style={{ backgroundColor: 'yellow', padding: '5px 5px 5px 5px' }} />
</div>
</Col>
</Row>
</Container>
</form>
</div>
);
};
--------------------------------------------------------------------------------------------------
const Quantity = (props) => {
const [count, setCount] = useState(0);
const increaseClick = () => {
setCount(count + 1 )
}
const decreaseClick = () => {
setCount(count - 1 )
}
return (
<>
<div style={{ display: 'flex', marginTop: '5%', marginLeft: '30%' }}>
<Button variant="primary" style={{ marginRight: '5%' }} onClick={decreaseClick}>-</Button>
<h3>{count}</h3>
<Button variant="primary" style={{ marginLeft: '5%' }} onClick={increaseClick}>+</Button>
</div>
</>
);
};
You have to create your state in parent and then pass to child, it will work.
const MainPart = () => {
const [count, setCount] = useState(0);
return (
...Your rest of code.
<Quantity count={count} setCount={setCount} />
)
}
Then In your child component, Use like this:
const Quantity = ({ count, setCount }) => {
const increaseClick = () => {
setCount(count + 1 )
}
const decreaseClick = () => {
setCount(count - 1 )
}
return (
<>
<div style={{ display: 'flex', marginTop: '5%', marginLeft: '30%'
}}>
<Button variant="primary" style={{ marginRight: '5%' }} onClick={decreaseClick}>-</Button>
<h3>{count}</h3>
<Button variant="primary" style={{ marginLeft: '5%' }} onClick={increaseClick}>+</Button>
</div>
</>
);
}
I have created a CRUD application and successfully it is performing all the operations.
But when I try to create a modal so that it shows up a warning either to delete the id or not on clicking delete. And If I try to delete a particular id from the modal I'm unable to delete the selected item, else it is deleted the latest id in the list.
What might be the problem that is making me not delete a particular id from the list only when creating a modal.
Help me how I can make it work.
This is the button to open the warning modal:
const [open, setOpen] = useState(false);
const toggle = () => setOpen(!open);
<button onClick={toggle}>
<MdIcons.MdDelete color='black' fontSize="1.3rem"/>delete</button>
This is the modal that opens after clicking delete:
<Modal isOpen={open} toggle={toggle}>
<ModalHeader toggle={toggle}>Warning</ModalHeader>
<ModalBody>Are you sure to delete this id from the list...</ModalBody>
<ModalFooter>
<Button onClick={() => onDelete(data.id)}>YES</Button>
<Button onClick={toggle}>Cancel</Button>
</ModalFooter>
</Modal>
In the above modal I have give the onclick event for button YES to delete the id selected, but the delete functionality is not working when I use it on a modal.
These are the button functionalities:
const getData = () => {
axios.get(`https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud`)
.then((getData) => {
setAPIData(getData.data);
})
}
const onDelete = (id) => {
axios.delete(`https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud/${id}`)
.then(() => {
getData();
})
}
Please help me how I can achieve the functionality of deleting the particular id after modal opens, and let me know if you need any more details regarding my code.
I am new to react, i don't know if my explanation will be correct, my theory is that the problem was this: You were rendering the modal for every record, and only the last modal remained.
I put the modal outside the loop, and i declared a useState to track the selected id to delete, it worked =D
Read.js :
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Table, Button, List, Popup, Grid, Icon, Dropdown, Menu, Header } from "semantic-ui-react";
import { useNavigate, Link } from "react-router-dom";
import * as MdIcons from "react-icons/md";
import * as AiIcons from "react-icons/ai";
import * as FiIcons from "react-icons/fi";
import { Modal, ModalFooter, ModalHeader, ModalBody } from "reactstrap";
import SideMenu from "../SideMenu/SideMenu";
function Read() {
const [APIData, setAPIData] = useState([]);
const [idToDelete, setIdToDelete] = useState(0);
useEffect(() => {
axios.get(`https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud`).then((response) => {
console.log(response.data);
setAPIData(response.data);
});
}, []);
const setData = (data) => {
let {
id,
image,
companyName,
email,
companyNumber,
uniqueNumber,
lineofBusiness,
companyRevenue,
openingTime,
closingTime,
discount,
rating,
address1,
address2,
pincode,
area,
city,
state,
country,
} = data;
localStorage.setItem("ID", id);
localStorage.setItem("Image", image);
localStorage.setItem("Email", email);
localStorage.setItem("Company Name", companyName);
localStorage.setItem("Company Number", companyNumber);
localStorage.setItem("Unique Number", uniqueNumber);
localStorage.setItem("Line of Business", lineofBusiness);
localStorage.setItem("Company Revenue", companyRevenue);
localStorage.setItem("Opening Time", openingTime);
localStorage.setItem("Closing Time", closingTime);
localStorage.setItem("Discount", discount);
localStorage.setItem("Rating", rating);
localStorage.setItem("Address1", address1);
localStorage.setItem("Address2", address2);
localStorage.setItem("Pincode", pincode);
localStorage.setItem("Area", area);
localStorage.setItem("City", city);
localStorage.setItem("State", state);
localStorage.setItem("Country", country);
};
const getData = () => {
axios.get(`https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud`).then((getData) => {
setAPIData(getData.data);
});
};
const onDelete = () => {
axios
.delete(`https://62c45bb0abea8c085a73b996.mockapi.io/Reactcrud/${idToDelete}`)
.then(() => {
navigate("/company/list");
toggle();
})
.then(() => {
getData();
});
};
let navigate = useNavigate();
const addUser = () => {
navigate("/company/create");
};
const [open, setOpen] = useState(false);
const toggle = () => setOpen(!open);
const [search, setSearch] = useState("");
return (
<>
<div className="container-fluid">
<div className="row">
<div className="col-lg-12" style={{ marginLeft: "-11px" }}>
<SideMenu />
</div>
</div>
<div className="row">
<div className="col-lg-3"></div>
<div className="col-lg-6">
<Button primary style={{ width: "150px", height: "40px" }} onClick={addUser}>
Add Company
</Button>
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search by any Category"
style={{
position: "absolute",
width: "260px",
height: "40px",
marginLeft: "285px",
border: "none",
fontSize: "15px",
padding: "8px",
borderRadius: "20px 20px 20px 20px",
}}
/>
<table style={{ width: "700px", height: "200px" }}>
<thead style={{ margin: "50px" }}>
<tr>
<th style={{ textAlign: "center" }}>List of Companies</th>
</tr>
</thead>
{APIData.filter((data) =>
Object.values(data).some((value) => value.toLowerCase().includes(search.toLowerCase()))
).map((data, id) => {
return (
<>
<tbody key={id}>
<li
style={{
minHeight: "140px",
borderRadius: "5px",
margin: "20px 0px",
listStyle: "none",
padding: "25px",
backgroundColor: "white",
boxShadow: "0 0 20px 0px rgba(0,0,0,0.2)",
}}
>
<tr>
<Link to="/company/view">
<button
style={{
background: "transparent",
border: "none",
color: "blue",
}}
onClick={() => setData(data)}
>
{data.companyName}
</button>
</Link>
</tr>
<tr>{data.companyNumber}</tr>
<tr>{data.uniqueNumber}</tr>
<tr>{data.lineofBusiness}</tr>
</li>
<div
style={{
position: "absolute",
marginLeft: "580px",
marginTop: "-120px",
}}
>
<Dropdown
icon={
<AiIcons.AiOutlineEllipsis
style={{
color: "black",
fontSize: "1.3rem",
marginTop: "15px",
marginLeft: "30px",
border: "1px solid black",
width: "30px",
height: "30px",
borderRadius: "50%",
}}
/>
}
pointing="top right"
>
<Dropdown.Menu>
<Dropdown.Item icon="edit" text="Edit">
<Link to="/company/edit">
<button
onClick={() => setData(data)}
style={{
background: "transparent",
border: "none",
}}
>
<FiIcons.FiEdit color="black" fontSize="1.3rem" /> Edit
</button>
</Link>
</Dropdown.Item>
<Dropdown.Item icon="delete" text="Delete">
<button
onClick={() => {
setIdToDelete(data.id);
toggle();
}}
style={{
background: "transparent",
border: "none",
}}
color="red"
>
<MdIcons.MdDelete color="black" fontSize="1.3rem" />
delete
</button>
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</div>
</tbody>
</>
);
})}
</table>
<Modal isOpen={open} toggle={toggle}>
<ModalHeader toggle={toggle}>Warning</ModalHeader>
<ModalBody>Are you sure to delete this id from the list...</ModalBody>
<ModalFooter>
<Button color="red" onClick={onDelete}>
Okay
</Button>
<Button color="primary" onClick={toggle}>
Cancel
</Button>
</ModalFooter>
</Modal>
</div>
</div>
</div>
</>
);
}
export default Read;
In a React project, I've created Chat Section. All designing and functionalities done, except that when messages are sent it doesn't automatically scroll down. What could be the best possible solution?
Here is the code for reference
const MessageApp = () => {
const [textValue, setTextValue] = useState("");
const [textMessages, setTextMessages] = useState([]);
const [newTextValue, setNewTextValue] = useState("");
const [showSenderMessage, setShowSenderMessage] = useState(false);
const [showRecieverMessage, setShowRecieverMessage] = useState(false);
useEffect(() => {
const newData = localStorage.getItem("messages");
setTextMessages(newData);
}, []);
const sendMessage = (e) => {
e.preventDefault();
setShowSenderMessage(true);
if (textValue != "") {
setTextMessages([...textMessages, textValue]);
localStorage.setItem("messages", textMessages);
setTextValue("");
} else {
return;
}
};
return (
<>
{showSenderMessage &&
textMessages.map((text) => (
<div
className="bubble-sender"
style={{
display: "flex",
flexWrap: "wrap",
justifyContent: "flex-start",
width: "80%"
}}
>
<span style={{ width: "20%" }}>
<img
alt="blank profile"
src="https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png"
style={{
height: "50px",
width: "50px",
border: "2px solid black",
borderRadius: "50%"
}}
/>
</span>
<span style={{ width: "80%" }}>
{text}
<br />
<span
style={{
display: "flex",
flexWrap: "wrap",
justifyContent: "flex-end"
}}
>
<small style={{ color: "grey", float: "right" }}>
11:23 AM
</small>
</span>
</span>
</div>
))}
<span>
<form
style={{
position: "fixed",
bottom: "0",
marginBottom: "80px",
width: "100%"
}}
>
<div className="col-lg-10 mb-3">
<div className="input-group mycustom">
<input
value={textValue}
type="text"
required
placeholder="Send Message"
maxLength="30"
onChange={(e) => setTextValue(e.target.value)}
/>
<div className="input-group-prepend">
<button
type="submit"
style={{
color: "white",
display: "flex",
flexWrap: "wrap",
justifyContent: "space-evenly"
}}
onClick={sendMessage}
>
Send Message
</button>
</div>
</div>
</div>
</form>
</span>
</>
);
};
export default MessageApp;
Following is the codesandbox link: https://codesandbox.io/s/upbeat-montalcini-bpdsp
try this:
import React, { useState, useEffect, useRef } from "react";
import "./MessageApp.css";
const MessageApp = () => {
const [textValue, setTextValue] = useState("");
const [textMessages, setTextMessages] = useState([]);
const [newTextValue, setNewTextValue] = useState("");
const [showSenderMessage, setShowSenderMessage] = useState(false);
const [showRecieverMessage, setShowRecieverMessage] = useState(false);
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
};
useEffect(scrollToBottom, [textMessages]);
useEffect(() => {
const newData = localStorage.getItem("messages");
setTextMessages(newData.split(","));
}, []);
const sendMessage = (e) => {
e.preventDefault();
setShowSenderMessage(true);
if (textValue != "") {
// const newTextValueHere = textValue;
// setNewTextValue(newTextValueHere);
// setTextValue("");
setTextMessages(preVal=>[...preVal,textValue]);
localStorage.setItem("messages", textMessages);
setTextValue("");
} else {
return;
}
};
return (
<>
{showSenderMessage &&
textMessages.map((text) => (
<div
className="bubble-sender"
style={{
display: "flex",
flexWrap: "wrap",
justifyContent: "flex-start",
width: "80%"
}}
>
<span style={{ width: "20%" }}>
<img
alt="blank profile"
src="https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png"
style={{
height: "50px",
width: "50px",
border: "2px solid black",
borderRadius: "50%"
}}
/>
</span>
<span style={{ width: "80%" }}>
{text}
<br />
<span
style={{
display: "flex",
flexWrap: "wrap",
justifyContent: "flex-end"
}}
>
<small style={{ color: "grey", float: "right" }}>
11:23 AM
</small>
</span>
</span>
</div>
))}
<span>
<form
style={{
position: "fixed",
bottom: "0",
marginBottom: "80px",
width: "100%"
}}
>
<div className="col-lg-10 mb-3">
<div className="input-group mycustom">
<input
value={textValue}
type="text"
required
placeholder="Send Message"
maxLength="30"
onChange={(e) => setTextValue(e.target.value)}
/>
<div className="input-group-prepend">
<button
type="submit"
style={{
color: "white",
display: "flex",
flexWrap: "wrap",
justifyContent: "space-evenly"
}}
onClick={sendMessage}
>
Send Message
</button>
</div>
</div>
</div>
</form>
</span>
<div ref={messagesEndRef} />
</>
);
};
export default MessageApp;
here a sandbox based on yours ( I just remove commented code).
I have fixed a bug on your setTextMessages where the app return an iterator error.
You will need to make some style adjustment because for now the new message is "hide" under the input field.
UPDATE
your const newData is typeOf string so you need to split it in your `setTexMessage()` like this:
useEffect(() => {
const newData = localStorage.getItem("messages");
setTextMessages(newData.split(","));
}, []);
I'm new to reactjs and I want an e-trade project. The problem is pressing the first "+" button, but increasing the number in the box next to it. How can I do this?
When I press the first, the other shouldn't increase because I will add more vegetable.
How can I solve this? Thank you so much
class App extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0
};
}
increment() {
this.setState(prevState => ({
counter: this.state.counter + 1
}));
}
decrement() {
if (this.state.counter === 0) {
this.setState({
counter: 0
});
} else {
this.setState(prevState => ({
counter: this.state.counter - 1
}));
}
}
render() {
return (
<div class="container">
<div class="row" style={{ marginTop: '50px' }}>
<Card className="col-md-3" style={{ }}>
<Card.Img variant="top" src="https://res.cloudinary.com/sivadass/image/upload/v1493620046/dummy-products/broccoli.jpg" style={{ width: '200px',marginLeft:'30px' }}/>
<Card.Body>
<Card.Title style={{ textAlign: 'center' }}> Brocoli - 1
</Card.Title>
<Card.Text style={{ textAlign: 'center' }}>
1 $
</Card.Text>
<div style={{ textAlign: 'center' }}>
<Button onClick={this.decrement.bind(this)}>-</Button>
<h2 value="1">{this.state.counter}</h2>
<Button onClick={this.increment.bind(this)}>+</Button>
</div>
</Card.Body>
</Card>
<Card className="col-md-3" style={{ marginLeft:'10px' }}>
<Card.Img variant="top" src="https://res.cloudinary.com/sivadass/image/upload/v1493620046/dummy-products/broccoli.jpg" style={{ width: '200px',marginLeft:'30px' }}/>
<Card.Body>
<Card.Title style={{ textAlign: 'center' }}> Brocoli - 1
</Card.Title>
<Card.Text style={{ textAlign: 'center' }}>
1 $
</Card.Text>
<div style={{ textAlign: 'center' }}>
<Button onClick={this.decrement.bind(this)}>-</Button>
<h2 value="1">{this.state.counter}</h2>
<Button onClick={this.increment.bind(this)}>+</Button>
</div>
</Card.Body>
</Card>
</div>
</div>
)
}
}
export default App;
Can you please check whether you are looking for the following type of solution or not? Please ignore the styling I have just implemented the functionality.
constructor(props) {
super(props);
this.state = {
items:[{
name:"Veg 1",
counter:0
},{
name:"Veg 2",
counter:0
}]
};
}
increment = (index) =>{
let localItems = [...this.state.items];
localItems[index].counter += 1;
this.setState({
...this.state,
items:[...localItems]
})
}
decrement = (index) =>{
let localItems = [...this.state.items];
localItems[index].counter -= 1;
this.setState({
...this.state,
items:[...localItems]
})
}
render() {
const { classes } = this.props;
return (
this.state.items.length ? this.state.items.map((item,index)=>{
return (
<div>
<button onClick={()=>this.increment(index)}>+</button>
<span>{item.name} - {item.counter}</span>
<button onClick={()=>item.counter && this.decrement(index)}>-</button>
</div>
)
}):null
)
}
Objective
Displaying only the fields that are filled in.
Background
In my application people will first fill out the application which has fields like "early reg fee, early reg date, regular reg fee, regular reg date" and so after they fill out all the information and click "view profile" they will see all the fields whether it's filled out or not.
If the value of one of the fields is null or undefined then it would not show up in the profile.
I was trying to do this and I started of by creating a state in the constructor "this.state {value: ''}"
class CompetitionProfileView extends React.Component {
constructor(props) {
super(props);
this.state {value: ''}
this.getContactCard = this.getContactCard.bind(this);
}
getCompetitionValue(path) {
const value = _.get(this.props.competition, path);
return value ? value : '';
}
getCompetitionDateValue(path) {
const value = _.get(this.props.competition, path);
return value ? value.toDateString() : '';
}
getCompetitionTimeValue(path) {
const value = _.get(this.props.competition, path);
return value ? `${
value.getHours() - 12
}:${value.getMinutes()}` : '';
}
getContactCard(num) {
return
this.getCompetitionValue(`Information.contactFirstName${num}`) ?
<Card key={num} style={{backgroundColor: '#f9f9f9', width: '32%'}} zDepth={2}>
<CardTitle title={`${this.getCompetitionValue(`Information.contactFirstName${num}`)} ${this.getCompetitionValue(`Information.contactFirstName${num}`)}`} subtitle={`${this.getCompetitionValue('Information.contactPosition1')}`} />
<Divider/>
<CardText>
<p style={{display: 'flex', justifyContent: 'center'}}><Phone/>{`${this.getCompetitionValue(`Information.contactFirstName${num}`)}`}</p>
<p style={{display: 'flex', justifyContent: 'center'}}><Email/>{`${this.getCompetitionValue(`Information.contactFirstName${num}`)}`}</p>
</CardText>
</Card>
:
'';
}
render(actions) {
return (
<div>
<div className="profileheader" style={{display: 'flex', flexDirection: 'column'}}>
<Paper className='banner-image' style={{backgroundImage: `url(${this.getCompetitionValue('Resources.boardPicture.url')})`,backgroundSize: 'cover',width: '100%', height: '200px', backgroundPositionY: '20%'}} zDepth={3}>
{/* <br style={{lineHeight: '15'}}/> */}
</Paper>
<Paper className='text-main' style={{textAlign: 'center'}}>
<label>{this.getCompetitionValue('Information.name')}</label>
</Paper>
<Paper className='logo-image' style={{backgroundImage: `url(${this.getCompetitionValue('Resources.competitionLogo.url')})`, backgroundSize: 'cover', width: '100px', height: '100px', marginTop: '-110px', marginLeft: '3%', paddingbottom: '20px'}} zDepth={3}/>
</div>
<hr/>
<div style={{display: 'flex', justifyContent: 'space-between'}}>
<Card style={{backgroundColor: '#f9f9f9', width: '49%'}} zDepth={2}>
<RaisedButton style={{display: 'flex', justifyContent: 'center'}} primary={true} label="Application Packet" onClick={() => window.open(this.getCompetitionValue('Resources.applicationPacket.url'), '_blank')}/>
</Card>
<Card style={{backgroundColor: '#f9f9f9', width: '49%'}} zDepth={2}>
<RaisedButton style={{display: 'flex', justifyContent: 'center'}} primary={true} label="Audition Video Info" onClick={() => window.open(this.getCompetitionValue('Resources.auditionVideoInfo.url'), '_blank')}/>
</Card>
</div>
<br/>
<div className='mainbody' style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-between'}}>
<br/>
<div className='rightbody' style={{display: 'flex', flexDirection: 'column', width: '60%', flexWrap: 'wrap'}}>
<Card style={{backgroundColor: '#F0EFEF'}} zDepth={2}>
<CardHeader title="About Us" />
<Divider/>
<CardText>{`${this.getCompetitionValue('Information.compBlurb')}`}</CardText>
</Card>
<br/>
<Card style={{backgroundColor: '#F0EFEF'}} zDepth={2}>
<CardHeader title="Application Information" />
<Divider/>
<CardText>
<p><b>Early Reg:</b>{` ${this.getCompetitionDateValue('Information.dueDateEarly')}`}</p>
<p><b>Early Reg Fee:</b>{` ${this.getCompetitionValue('Information.earlyDues')}`}</p>
<p><b>Regular Reg:</b>{` ${this.getCompetitionDateValue('Information.dueDateRegular')}`}</p>
<p><b>Regular Reg Fee:</b>{` ${this.getCompetitionValue('Information.regularDues')}`}</p>
<p><b>Late Reg:</b>{` ${this.getCompetitionDateValue('Information.dueDateLate')}`}</p>
<p><b>Late Reg Fee:</b>{` ${this.getCompetitionValue('Information.lateDues')}`}</p>
<p><b>Applications Due At:</b>{` ${this.getCompetitionTimeValue('Information.dueTime')}`}</p>
<p><b>Time Zone:</b>{` ${this.getCompetitionValue('Information.timeZone')}`}</p>
<p><b>Penalties:</b>{` ${this.getCompetitionValue('Information.extraFees')}`}</p>
<p><b>Hear Back Date:</b>{` ${this.getCompetitionDateValue('Information.hearbackDate')}`}</p>
<p><b>Payment Method:</b>{` ${this.getCompetitionValue('Information.paymentMethods')}`}</p>
<br/>
</CardText>
</Card>
</div>
</div>
<br/>
<div className="contactinfo" style={{display: 'flex', justifyContent: 'space-around'}}>
{[1,2,3].map((num) => this.getContactCard(num))}
</div>
<br/>
{this.props.competition.Board.length > 0 &&
<Card style={{backgroundColor: '#F0EFEF'}} zDepth={2}>
<Table >
<TableHeader adjustForCheckbox={false} displaySelectAll={false}>
<TableRow>
{ Object.keys(this.props.competition.Board[0]).map((key) => <TableHeaderColumn key={key}>{key}</TableHeaderColumn>) }
</TableRow>
</TableHeader>
<TableBody displayRowCheckbox={false}>
{this.props.competition.Board.map((row, i) => (
<TableRow key={i}>
{ Object.keys(row).map((column) => <TableRowColumn key={column}>{row[column].name ? row[column].name : row[column]}</TableRowColumn>) }
</TableRow>
))
}
</TableBody>
</Table>
</Card>
}
</div>
);
}
}
const mapStateToProps = (state) => {
return {
messages: state.messages
};
};
export default connect(mapStateToProps)(CompetitionProfileView);
You can use if statements in your render() function, like so:
render() {
if (this.props.thing1) {
return <h1>Thing 1</h1>
} else {
return (
<div className="warning">
<h2>Thing 2</h2>
</div>
)
}
}
You can even use functions in the render() function like this:
renderASmallPart() {
if (this.props.thing1) {
return <h1>Thing 1</h1>
} else {
return (
<div className="warning">
<h2>Thing 2</h2>
</div>
)
}
}
render() {
return (
<div>
<h1>My App</h1>
<h2>Here's a thing:</h2>
{this.renderASmallPart()}
</div>
)
}
You can use this to break up your large render() function into smaller functions that check what the value of their field is and only render something when the field has a non-empty value
You need to look into Conditional Rendering and only render that element when there is a value.
https://facebook.github.io/react/docs/conditional-rendering.html
https://atticuswhite.com/blog/render-if-conditionally-render-react-components/
http://devnacho.com/2016/02/15/different-ways-to-add-if-else-statements-in-JSX/
https://kylewbanks.com/blog/how-to-conditionally-render-a-component-in-react-native