buttons styling in confirm Modal - reactjs

I have project and this project contains many of interfaces, and among these interfaces, there are interface to upload image, and i have delete button on this image to confirm delete image operation,
and as u can see on the image, there are two buttons, i don't know how can put style to these buttons, i need to put marginRight to "buttons"
how can i solve the problem?
const onGalleryFileRemove = (_file: UploadFile<any>) => {
const { confirm } = Modal
return new Promise<boolean>((resolve, reject) => {
confirm({
title: <h3 style={{ marginLeft: '3rem' }}>{formatMessage({ id: 'confirmationDeletePicture' })}</h3>,
icon: <ExclamationCircleOutlined style={{ float: 'right' }} />,
onOk: () => {
resolve(true)
},
onCancel: () => {
reject(true)
}
})
});
};

You can pass style in okButtonProps and cancelButtonProps props.
Modal.confirm({
content: 'Hello World',
cancelButtonProps: {
style: {
marginRight: '10px'
}
},
okButtonProps: {
style: {
marginRight: '10px'
}
}
});

Related

Unexpected go back on react-navigation

I have a nested stack in my project. Everything works fine but when I click a button that takes you to a page where at first it has to load the user list with useEffect, the page does a navigation.goBack (). If I take useEffect off the page, when I click the button it goes to the right page.
listaUtenti: async () => {
setLoad(true);
getAuth().currentUser.getIdToken(true).then(function(idToken) {
fetch('http://ipipip/users', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + idToken,
}
}).then((response) => {
return (response.json())
}).
then((response) => {
console.log(response);
if(response.status === 403){
throw new Error(response.message);
}
setLoad(false);
})
.catch(function(error) {
setLoad(false);
console.log(error);
showMessage({
message: "Attenzione",
description: String(error),
type: "danger",
backgroundColor: '#FF3D71',
color: '#FFFFFF',
statusBarHeight: 0,
style: { borderRadius: 10, marginTop: Constants.statusBarHeight + 10, width: '90%', alignSelf: 'center' }
});
})
}).catch(function(error) {
setLoad(false);
console.log(error);
showMessage({
message: "Attenzione",
description: error.message,
type: "danger",
backgroundColor: '#FF3D71',
color: '#FFFFFF',
statusBarHeight: 0,
style: { borderRadius: 10, marginTop: Constants.statusBarHeight + 10, width: '90%', alignSelf: 'center' }
});
})
},
In my HomePage i have a button that on press navigate to ListaUtentiScreen
<Button style={{marginVertical:10}} onPress={() => {navigation.navigate('ListaUtenti')}}>Lista utenti</Button>
I call "listaUtenti()" in useEffect
const BackIcon = (props) => (
<Icon {...props} name='arrow-back' />
);
export default function ListaUtentiScreen({navigation}) {
const { tema, listaUtenti } = useContext(AuthContext);
const [utenti, setUtenti] = useState({});
const ref = useRef(null);
useScrollToTop(ref);
const navigateBack = () => {
navigation.goBack();
};
const BackAction = () => (
<TopNavigationAction icon={BackIcon} onPress={navigateBack}/>
);
useEffect(() => {
const lista = async () => {
const users = await listaUtenti();
setUtenti(users);
};
lista();
return () => {
setUtenti({});
};
});
return (
<>
<TopNavigation title='Lista utenti' alignment='center' accessoryLeft={BackAction}/>
<Divider/>
<KeyboardAwareScrollView ref={ref} extraHeight={100} enableOnAndroid={true} scrollEnabled={true} contentContainerStyle={{flexGrow:1}} style={{backgroundColor: tema ? '#151A30' : '#EDF1F7'}}>
<Layout style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: tema ? '#151A30' : '#EDF1F7' }}>
<Text>Hello</Text>
</Layout>
</KeyboardAwareScrollView>
</>
);
}
if I remove useEffect, it navigates to listaUtenti but if I use useeffect it goes back. If I try to use console.log () to see if the function is used, on the terminal it prints the user list but it goes back anyway
This is a video that show the error
Without a code snippet its pretty hard to answer, however my intuition tells me you're doing something like this
<Button onPress={navigation.goBack()}> {Back arrow in the top left corner} </Button>
When you should be doing something like this:
<Button onPress={(e)=>navigation.goBack()}> {Back arrow in the top left corner} </Button>
The difference here is the (e) => inside the onPress/onClick (depending on what framework you're using) without the (e) => the function is called immediately when the button is rendered. Again, not 100% sure without the code snippet

How does one render a component being passed in as a key of an object that is a prop?

I am creating a table component and I am looking to pass in custom react components if the user requires them. The TableCell.component looks like the following:
const TableCell = ({ isHeader = false, title, TitleComponent, position = defaultPosition, ...props }: TableCellProps ) => {
if (isHeader) {
return (
<TableHeaderComponent position={position} {...props}>
{TitleComponent ? TitleComponent : title}
</TableHeaderComponent>
);
}
return (
<TableCellComponent position={position} {...props}>
{title}
</TableCellComponent>
);
};
I am hoping to call the table as the following:
return <Table
header={{
children: 'Your Table Header',
variant: TextType.h2,
}}
rows={[
{ title: 'Click Me For Function', onClick: () => alert('hiya') },
{ title: 'Center Aligned Header', position: 'center' },
{ title: 'Right Aligned Header', position: 'right' },
]}
cells={[
[
{ TitleComponent: <CustomComponent {...props} /> },
{ title: 'Center Aligned', position: 'center' },
{ title: 'Right Aligned', position: 'right' },
],
]}
/>;
When I run this I can't seem to get the component that is passed in as the output. Any ideas what I am doing wrong. I see some errors around no call signatures but I don't understand why that is happening.
Cheer,
I figured out that the best way to do this for my use case was to pass in the constructor to the Object which in this case would be CustomComponent and then pass another object with the props and instantiate it where I needed it.

How to implement react-dnd useDragLayer?

I have a component that currently uses the useDrag hook to connect to react-dnd. It works well, except for previews. I want to implement useDragLayer instead to see if it would help with my preview problems, as many online threads suggest.
This is my current (simplified) useDrag implementation:
const [{ isDragging }, connectDragSource, connectPreview] = useDrag({
item,
collect: monitor => ({
isDragging: monitor.getItem()?.index === item.index,
})
})
return (
<Wrapper ref={connectPreview} isDragging={isDragging}>
<DragHandle ref={connectDragSource} />
</Wrapper>
)
How do I use useDragLayer in this context, in a way that might help with my previews? The docs example makes little sense to me...
How do I connect my rendered components using useDragLayer api? useDragLayer doesn't return drag source and preview connector functions (like useDrag does on index 1 and 2 of the returned array), and its collect function doesn't provide a DragSourceConnector instance either. So what do I do with the hook/returned value after I call it?
I just resolved this and want to share it to help others :)
You will need to do couple of things for this to fully work.
Disable the default preview behavior by adding the following useEffect
import { getEmptyImage } from "react-dnd-html5-backend";
const [{ isDragging }, drag, dragPreview] = useDrag(() => ({
type: "BOX",
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
}));
useEffect(() => {
dragPreview(getEmptyImage(), { captureDraggingState: true });
}, []);
Create the custom default layer
export const CustomDragLayer = (props: {}) => {
const {
itemType,
isDragging,
initialCursorOffset,
initialFileOffset,
currentFileOffset,
} = useDragLayer((monitor) => ({
item: monitor.getItem(),
itemType: monitor.getItemType(),
initialCursorOffset: monitor.getInitialClientOffset(),
initialFileOffset: monitor.getInitialSourceClientOffset(),
currentFileOffset: monitor.getSourceClientOffset(),
isDragging: monitor.isDragging(),
}));
if (!isDragging) {
return null;
}
return (
<div style={layerStyles}>
<div
style={getItemStyles(
initialCursorOffset,
initialFileOffset,
currentFileOffset
)}
>
<div>Your custom drag preview component logic here</div>
</div>
</div>
);
};
const layerStyles: CSSProperties = {
position: "fixed",
pointerEvents: "none",
zIndex: 100,
left: 0,
top: 0,
width: "100%",
height: "100%",
border: "10px solid red",
};
function getItemStyles(
initialCursorOffset: XYCoord | null,
initialOffset: XYCoord | null,
currentOffset: XYCoord | null
) {
if (!initialOffset || !currentOffset || !initialCursorOffset) {
return {
display: "none",
};
}
const x = initialCursorOffset?.x + (currentOffset.x - initialOffset.x);
const y = initialCursorOffset?.y + (currentOffset.y - initialOffset.y);
const transform = `translate(${x}px, ${y}px)`;
return {
transform,
WebkitTransform: transform,
background: "red",
width: "200px",
};
}
Add the <CustomDragLayer /> to the top-level component
You will need to include the ref={drag} to the component you want to drag and remove the connectPreview ref completely.
Hopefully, this helps you.

I have a card component that I need to update to add new items

I built a card component that shows a list of user data and images with antd on nextJs. I want to build a functionality that creates a modal to input new data and image and adds it to the user interface as a new card, but I am confused on how to get my hands around it. I need assistance. Here's a link to my code!
import React from 'react';
import { Avatar, Card, Icon, List } from 'antd';
import { ICON_LIST, LIST_TEXTS, STYLES, USER_UPLOAD } from './constants';
const { AVATAR, CARD_CONTAINER, ICON, USER_LIST } = STYLES;
const { INNER, MORE, UPLOAD, VERTICAL } = LIST_TEXTS
class Home extends React.Component {
state = {
clicks: 0,
};
IncrementIconText = () => {
this.setState({ clicks: this.state.clicks + 1 });
}
render() {
const actions = ( ICON_LIST.map(({ type }) => (
<span>
<Icon key={type} type={type} onClick={this.IncrementIconText} style={ICON} />
{this.state.clicks}
</span>
)));
return (
<List
itemLayout={VERTICAL}
dataSource={USER_UPLOAD}
renderItem={item => (
<List.Item style={USER_LIST}>
<Card
actions={actions}
cover={<img alt={UPLOAD} src={item.image} />}
extra={<Icon type={MORE} />}
hoverable
title={<a><Avatar src={item.image} style={AVATAR} />{item.user}</a>}
type={INNER}
style={CARD_CONTAINER}
>
{item.story}
</Card>
</List.Item>
)}
/>
);
}
}
export default Home;
constants.js
export const ICON_LIST = [
{
key: "heart",
type: "heart",
},
{
key: "dislike",
type: "dislike",
},
{
key: "meh",
type: "meh",
},
]
export const LIST_TEXTS = {
INNER: "inner",
MORE: "more",
UPLOAD: "upload",
VERTICAL: "vertical",
};
export const STYLES = {
AVATAR: {
marginRight: 8
},
CARD_CONTAINER: {
width: "650px",
marginBottom: 50
},
ICON: {
marginRight: 8
},
USER_LIST: {
width: "100%",
display: "flex",
justifyContent: "center",
alignItems: "center"
},
};
export const USER_UPLOAD = [
{
image: "http://sugarweddings.com/files/styles/width-640/public/1.%20The%20Full%20Ankara%20Ball%20Wedding%20Gown%20#therealrhonkefella.PNG",
story: "Today's my birthday next week! What do you think?",
user: "Chioma",
},
{
image: "https://dailymedia.com.ng/wp-content/uploads/2018/10/7915550_img20181007141132_jpeg01c125e1588ffeee95a6f121c35cd378-1.jpg",
story: "Going for an event. Do you like my outfit",
user: "Simpcy",
},
{
image: "https://i0.wp.com/www.od9jastyles.com/wp-content/uploads/2018/01/ankara-styles-ankara-styles-gown-ankara-tops-ankara-gowns-ankara-styles-pictures-latest-ankara-style-2018-latest-ankara-styles-ankara-ankara-styles.png?fit=437%2C544&ssl=1",
story: "Saturdays are for weddings. Yay or nay!",
user: "Angela",
},
]
So this could get you started:
https://codesandbox.io/s/1r7j6lom34?fontsize=14
I moved your static USER_UPLOAD into the state of Home and wrote a method to add a new upload to that state.
You would now need to come up with a component that shows your modal and calls AddUpload with the right values.
Also your card-actions don't seem to function properly. To fix that i suggest creating a wrapper component for Card that has a state with the appropriate click counters. That way every card has its own clickcounters.

Module Error Requiring unknown module

Hello am having a problem I am using react native am a newbie and I am creating a app that has some tabs but what i want is when i click the tab each as its own navigation bar.
I follow [AppCoda Example][1] but i notice that code base is different from the new code base react native. my code is bellow. Remember am trying to get a Nav bar for each tabs an i created a folder structure to require each tab in but am getting that unknown module when i know its there. Just to add if i add the same code which was in sub folder in the index.os.js it works look below:
'use strict';
var React = require('react-native');
var SearchButton = require('./app/components/buttons/searchButton');
var CameraButton = require('./app/components/buttons/cameraButton');
var ProfileButton = require('./app/components/buttons/profileButton');
var ContactButton = require('./app/components/buttons/contactButton');
var {
AppRegistry,
TabBarIOS,
NavigatorIOS,
StyleSheet,
Text,
View
} = React;
class AwesomeProject extends React.Component{
constructor(props) {
super(props);
this.state = {
selectedTab: 'Search'
};
}
render() {
return (
<TabBarIOS selectedTab={this.state.selectedTab} barTintColor="darkslateblue">
<TabBarIOS.Item
selected={this.state.selectedTab === 'Search'}
systemIcon="search"
onPress={() => {
this.setState({
selectedTab: 'Search'
});
}} style={styles.container} >
<SearchButton/>
</TabBarIOS.Item>
<TabBarIOS.Item systemIcon="bookmarks"
selected={this.state.selectedTab === 'Camera'}
icon={{uri:'Camera'}}
onPress={() => {
this.setState({
selectedTab: 'Camera'
});
}}>
<CameraButton/>
</TabBarIOS.Item>
<TabBarIOS.Item systemIcon="history"
selected={this.state.selectedTab === 'Profile'}
icon={{uri:'Profile'}}
onPress={() => {
this.setState({
selectedTab: 'Profile'
});
}}>
<ProfileButton/>
</TabBarIOS.Item>
<TabBarIOS.Item systemIcon="contacts"
selected={this.state.selectedTab === 'Contacts'}
icon={{uri:'Contacts'}}
onPress={() => {
this.setState({
selectedTab: 'Contacts'
});
}}>
<ContactButton/>
</TabBarIOS.Item>
</TabBarIOS>
);
}
};
var styles = StyleSheet.create({
navigator: {
flex: 1,
},
tabContent: {
flex: 1,
alignItems: 'center', },
tabText: {
color: 'white',
margin: 50, },
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
Now in the search button which should get the search title from a navigation folder thats where the problem is its saying unknown module
'use strict';
var React = require('react-native');
var searchTitle = require('./app/components/navigation/searchTitle');
var {
StyleSheet,
View,
NavigatorIOS,
Text
} = React
var styles = StyleSheet.create({
navigator: {
flex: 1
}
}
);
class Search extends React.Component{
render() {
return (
<NavigatorIOS
style={styles.navigator}
initialRoute={{
title: 'SomeTitle',
component: searchTitle
}}/>
);
}
}
module.exports = Search;
can some one help me with this.
You are asking require to search a relative path. From your examples I see that searchButton is in ./app/components/buttons/ and searchTitle is in ./app/components/navigation/, so if you want to require searchTitle from searchButton the path you need to specify is ../navigation/searchTitle.
var back_bg = require('./../img/menu.png');

Resources