How to use semantic-ui-react dropdown - reactjs

I am trying to use semantic-ui-react with typescript to create a form . So I am using the documentation. However when I implement the dropdow or the form I am getting a basic HTML form without CSS. What should I do to get the same UX as react.semantic-ui.com
import { Dropdown } from 'semantic-ui-react'
const options = [
{ key: 1, text: 'Location 1', value: 1 },
{ key: 2, text: 'Location 2', value: 2 },
{ key: 3, text: 'Location 3', value: 3 },
]
return (
<Form>
<div>
<Dropdown
placeholder='Etat *'
title="Select Etat"
fluid
selection
options={StatusOptions}
/>
</div>
</Form>

You need to install the default theme using npm npm i semantic-ui-css
And later import that theme in your app.ts or index.ts
import 'semantic-ui-css/semantic.min.css'

Similar to the above answer by Fayeed. You can import the the CSS CDN in the header tag of index.html
For example:
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/semantic-ui#2.4.2/dist/semantic.min.css" />

Related

How to create a dynamic Material UI Icon Atom in StoryBook and React TypeScript?

I am using StoryBook with React, TypeScript, and Material UI. I want to create an Icon Atom that behaves dynamically so that it can render the icon which I want to pass in as a prop.
Right Now, I am using the below-mentioned approach, but there are some problems with this.
I am unable to change the Icon for a particular story. That's not the dynamic behavior I want.
I also want to pass in some props such as fontSize and color to my Material UI Icon so that it can use them to render differently based on the value of props.
I want my component to behave according to the above two points. Please help !!
Icon.stories.tsx File
import React from "react";
import { ComponentStory, ComponentMeta } from "#storybook/react";
import MyIcon from "./Icon";
import AccessTimeIcon from "#mui/icons-material/AccessTime";
import PersonOutlineIcon from "#mui/icons-material/PersonOutline";
export default {
title: "Atoms/MyIcon",
component: MyIcon,
argTypes: {
color: {
options: [
"primary",
"secondary",
"warning",
"error",
"info",
"success",
"action",
],
control: { type: "radio" },
},
fontSize: {
options: ["small", "medium", "large"],
control: { type: "radio" },
},
},
} as ComponentMeta<typeof MyIcon>;
const Template: ComponentStory<typeof MyIcon> = (args) => <MyIcon {...args} />;
export const Clock = Template.bind({});
Clock.args = {
fontSize: "medium",
color: "primary",
materialIcon: <AccessTimeIcon />,
};
export const Person = Template.bind({});
Person.args = {
fontSize: "large",
color: "warning",
materialIcon: <PersonOutlineIcon />,
};
Icon.tsx File
import React from "react";
import type { IconProps } from "#mui/material/Icon";
interface MyIconProps extends IconProps {
materialIcon: React.ReactElement;
}
const MyIcon = ({ materialIcon, fontSize, color }: MyIconProps) => {
return <>{materialIcon}</>;
};
export default MyIcon;
One approach is to use a library like material-icons-react which provides a react component that you can render with custom props.
import MaterialIcon, {colorPalette} from 'material-icons-react';
<MaterialIcon icon="dashboard" />
// different sizes
<MaterialIcon icon="dashboard" size='large' />
<MaterialIcon icon="dashboard" size={100} />
// colours
<MaterialIcon icon="dashboard" color={colorPalette.amber._200} />
<MaterialIcon icon="dashboard" color={colorPalette.amber.A700} />
<MaterialIcon icon="dashboard" color='#7bb92f' />
Another approach is including the material icons via Google Web Fonts script.
Add this to your html entry point:
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
Then you can use the material-icons class name and put the icon name inside the element:
<span class="material-icons">access_time_icon</span>
You can put this rendering in you Icon component and pass any styling props you want.
Note that if you use other icon variants, e.g. outlined, you need to add a separate font for each variant and use a different class like material-icons-outlined.
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<span class="material-icons">access_time_icon</span>

code block not displaying when previewing in react-quill

In this code, I am trying to insert a code block using react-quilljs
import React, { useState } from 'react';
import hljs from 'highlight.js';
import { useQuill } from 'react-quilljs';
import 'quill/dist/quill.snow.css'; // Add css for snow theme
export default () => {
hljs.configure({
languages: ['javascript', 'ruby', 'python', 'rust'],
});
const theme = 'snow';
const modules = {
toolbar: [['code-block']],
syntax: {
highlight: (text) => hljs.highlightAuto(text).value,
},
};
const placeholder = 'Compose an epic...';
const formats = ['code-block'];
const { quill, quillRef } = useQuill({
theme,
modules,
formats,
placeholder,
});
const [content, setContent] = useState('');
React.useEffect(() => {
if (quill) {
quill.on('text-change', () => {
setContent(quill.root.innerHTML);
});
}
}, [quill]);
const submitHandler = (e) => {};
return (
<div style={{ width: 500, height: 300 }}>
<div ref={quillRef} />
<form onSubmit={submitHandler}>
<button type='submit'>Submit</button>
</form>
{quill && (
<div
className='ql-editor'
dangerouslySetInnerHTML={{ __html: content }}
/>
)}
</div>
);
};
Using the above code, I get the following preview of the editor's content
There are two problems with this:
There is no code syntax highlighting, as I want to achieve this using the highlihgt.js package, inside the code block inside the editor, and
The code block is not displayed (with the black background and highlighting syntax when it's working) in the previewing div outside the editor.
How can I fix these two issues?
Your code is getting marked up by highlight.js with CSS classes:
<span class="hljs-keyword">const</span>
You are not seeing the impact of those CSS classes because you don't have a stylesheet loaded to handle them. You need to choose the theme that you want from the available styles and import the corresponding stylesheet.
import 'highlight.js/styles/darcula.css';
Look at the css in the editor mode. It depends on two class names ql-snow and ql-editor.
You can fix this issue by wrapping it around one more div with className ql-snow.
<div className='ql-snow'>
<div className='ql-editor' dangerouslySetInnerHTML={{ __html: content }}>
<div/>
</div>
This should work.
I got the same issue and when I used hjls what happened was that I got syntax highlighting in the editor but not in the value.
If you noticed the syntax gets highlighted some seconds after you write the code block, this means that the value gets set before the syntax gets highlighted.
So, I just set the value after 2 seconds using setTimeout and this solved my problem
Like this:
<ReactQuill
theme="snow"
value={value}
onChange={(content) => {
setTimeout(() => {
setValue(content)
}, 2000)
}}
modules={modules}
formats={formats}
bounds="#editor"
placeholder="Write something..."
className="text-black dark:text-white"
/>
I recently implemented this logic into my project. I used React Quill for the text editor, implemented syntax highlighting to it using highlight.js, and I also used React Markdown to display the formatted content on my website. React Markdown by default works with markdown, so you need a plugin (rehype-raw) to get it to parse HTML. This is my code, from my project. Just remove some of the unnecessary stuff from here that is specific to my project and use what you need.
// PLUGINS IMPORTS //
import { Typography } from "#mui/material";
import { useEffect, useState } from "react";
import hljs from "highlight.js";
import "react-quill/dist/quill.core.css";
import "react-quill/dist/quill.snow.css";
import "highlight.js/styles/atom-one-dark.css";
import ReactQuill from "react-quill";
import ReactMarkdown from "react-markdown";
import rehypeRaw from "rehype-raw";
// COMPONENTS IMPORTS //
import { CreateButton } from "components/atoms";
// EXTRA IMPORTS //
import styles from "./create-post.module.css";
import { ETheme } from "types/theme";
/////////////////////////////////////////////////////////////////////////////
type CreatePostProps = {};
hljs.configure({
// optionally configure hljs
languages: ["javascript", "python", "c", "c++", "java", "HTML", "css", "matlab"],
});
const toolbarOptions = [
["bold", "italic", "underline", "strike"],
["blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
["link"],
[{ indent: "-1" }, { indent: "+1" }],
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ align: [] }],
];
const modules = {
syntax: {
highlight: function (text: string) {
return hljs.highlightAuto(text).value;
},
},
toolbar: toolbarOptions,
clipboard: {
// toggle to add extra line breaks when pasting HTML:
matchVisual: false,
},
};
const formats = [
"header",
"font",
"size",
"bold",
"italic",
"underline",
"strike",
"blockquote",
"code-block",
"list",
"bullet",
"indent",
"link",
"align",
];
const placeholder = "Description";
const CreatePost = (props: CreatePostProps) => {
const [markdownText, setMarkdownText] = useState("");
useEffect(() => {
console.log({ markdownText });
}, [markdownText]);
return (
<main className={`${styles["create-post-wrapper"]}`}>
<header className={`${styles["create-post-header"]}`}>
<Typography variant="h6">Create a post</Typography>
</header>
{/* making the border a seperate div makes it easier to apply margin */}
<div className={`${styles["border"]} ${styles["top"]}`}></div>
<div>Choose a community</div>
<article className={`${styles["create-post"]}`}>
<section className={`${styles["inner-create-post"]}`}>
<section>Title</section>
<ReactQuill
value={markdownText}
onChange={value => setMarkdownText(value)}
theme="snow"
modules={modules}
formats={formats}
placeholder={placeholder}
/>
<div className="ql-snow">
<div className="ql-editor">
<ReactMarkdown children={markdownText} rehypePlugins={[rehypeRaw]} />
</div>
</div>
<div className={`${styles["border"]} ${styles["bottom"]}`}></div>
<section className={`${styles["post-button"]}`}>
<CreateButton
theme={ETheme.LIGHT}
buttonText="Post"
buttonProps={{
fullWidth: false,
}}
/>
</section>
</section>
</article>
</main>
);
};
export default CreatePost;
You can always add more options to toolbarOptions, but don't forget to also add them to formats if you do. Also, if you want to keep formatting anywhere else in your website, you need the two divs with these 2 classes around your markdown.
React Quill bacially saves everything into a string with HTML and classes, you import styles for those classes and it works like magic.

React Select Example not displaying dropdown

I am just trying a React Select Dropdown Example using the below code:
import React from 'react';
import Select from 'react-select';
import '../../../node_modules/bootstrap/dist/css/bootstrap.min.css';
const techCompanies = [
{ label: "Apple", value: 1 },
{ label: "Facebook", value: 2 },
{ label: "Netflix", value: 3 },
{ label: "Tesla", value: 4 },
{ label: "Amazon", value: 5 },
{ label: "Alphabet", value: 6 },
]
const App = () => {
return (
<div className="container">
<div className="row">
<div className="col-md-4" />
<div className="col-md-4">
<Select options={ techCompanies } />
</div>
<div className="col-md-4" />
</div>
</div>
)
};
export default App
Before this , I installed react select
npm i react-select
also installed bootstrap
npm install bootstrap --save
But after running I am getting the error:
Unable to resolve "../../../node_modules/bootstrap/dist/css/bootstrap.min.css" from "components/university/App.js"
Failed building JavaScript bundle.
I can see the bootstrap.min.css under node_modules folder.
If I comment the import I am get the following :
View config not found for name div. Make sure to start component names with a capital letter.
Can anyone tell where am I going wrong?Thanks in Advance.
You can't use html components or the usual web css in react-native. In contrast to react web, react-native will map your components to native android, ios or windows ui components. Therefore your components must be composited of react-native components. I think you should check out this answer which explains the difference between react and react-native in more depth.
In your case you could start with an App Component similiar to this:
import React, { useState } from "react";
import { View, Picker, StyleSheet } from "react-native";
const techCompanies = [
{ label: "Apple", value: 1 },
{ label: "Facebook", value: 2 },
{ label: "Netflix", value: 3 },
{ label: "Tesla", value: 4 },
{ label: "Amazon", value: 5 },
{ label: "Alphabet", value: 6 },
]
const App = () => {
const [selectedValue, setSelectedValue] = useState(1);
return (
<View style={styles.container}>
<Picker
selectedValue={selectedValue}
style={{ height: 50, width: 150 }}
onValueChange={itemValue => setSelectedValue(itemValue)}
>
{techCompanies.map(({ label, value }) =>
<Picker.Item label={label} value={value} key={value} />)}
</Picker>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 40,
alignItems: "center"
}
});
export default App;
see https://reactnative.dev/docs/picker for reference.
Old answer, before we learned that this is about react-native:
Your original code actually looked fine and should work.
However the css import should usually be your first import, because you want styles inside imported components to take precedence over the default styles. source
The added braces and return are not needed at all...
Also I would recommend using
import 'bootstrap/dist/css/bootstrap.min.css'
instead of
import '../../../node_modules/bootstrap/dist/css/bootstrap.min.css'. The Babel+Webpack setup of create-react-app will take care of figuring out the location of the bootstrap module. If you use a relative path instead, there will be errors as soon as you move the file with the import...
Maybe something went wrong during your package installation? I'd suggest that you just try this:
rm -rf ./node_modules
npm install
npm run start
You can verify that your code was working in this sandbox: https://codesandbox.io/s/react-select-bootstrap-sample-g2264?file=/src/App.js
Your import looks fine. Sometimes the error messages throw us off track, as the real error is caused by some other compiling issue. So, try fixing this first:
You are confusing parentheses and curly braces. Plus, you are missing a return. Should be:
const App = () => {
return (
<div className="container">
<div className="row">
<div className="col-md-4" />
<div className="col-md-4">
<Select options={ techCompanies } />
</div>
<div className="col-md-4" />
</div>
</div>
);
};

Css being overridden?

I'm using material ui for a react app. I'm also using material table. My nav bar just uses the default styling that material ui provides. This has been working fine. However when I add material table to the page, the nav bar goes from blue to white! I'm not sure how to resolve this. The code is below:
class ProfilePage extends React.Component {
render() {
const rows = [
{ title: "Time", field: "time" },
{ title: "Type", field: "type" },
{ title: "Feature", field: "feature" },
{ title: "Weight", field: "weight" }
];
const {Profile, error, match } = this.props;
const features = Profile;
const userId = `ID: ${match.params.userId}`;
if (error || Object.entries(tasteProfile).length === 0) {
toastr.error(error);
featureTable = <h2>Couldn't find profiles for that id</h2>;
}
return (
<div>
<NavBar />
<Typography id="userId" variant="h6" color="inherit">
{userId}
</Typography>
<Paper>
<div>
<MaterialTable
title="Profiles"
columns={rows}
data={features["features"]}
>
</MaterialTable>
</div>
</Paper>
</div>
);
}
}
Grateful for any help!
Try using the same versions of material-ui/core and material-ui/icons that material-table uses as seen in the package-lock.json file. I was able to fix my AppBar CSS style issue by downgrading these to the same version.
npm uninstall #material-ui/core
npm uninstall #material-ui/icons
npm install #material-ui/core#4.0.1
npm install #material-ui/icons#4.0.1
Have you tried including the Material table stylesheet before the Material UI kit one?

React Material UI, how do I make mobile friendly selects?

I am working on a React project and I am using Material UI.
Versions:
├─ react#15.6.1
├─ material-ui#0.19.4
I have in my code a component that makes use of Select Field component.
My code looks something like this:
<SelectField some_props>
{some_list.map(() => {return <MenuItem other_props/>})}
</SelectField>
On a desktop, this looks very good. However, I would like to get the native mobile select. The rolling one.
Basically, this:
How do I get a mobile friendly rolling select with Material UI?
Thanks!
Here is an example component which uses react-device-detect. If the user isMobile, the native select/options are rendered.
import React from 'react';
import {isMobile} from 'react-device-detect';
import FormControl from '#material-ui/core/FormControl';
import InputLabel from '#material-ui/core/InputLabel';
import Select from '#material-ui/core/Select';
import MenuItem from '#material-ui/core/MenuItem';
const ExampleSelect = () => {
const value = null;
const onChange = (e) => console.log(e.target.value);
const options = [
{value: 1, label: 'Option 1'},
{value: 2, label: 'Option 2'},
{value: 3, label: 'Option 3'}
];
return (
<FormControl>
<InputLabel>
Options
</InputLabel>
<Select
native={isMobile}
value={value}
onChange={onChange}
>
{options.map(option => (
isMobile ? (
<option key={option.value} value={option.value}>{option.label}</option>
) : (
<MenuItem key={option.value} value={option.value}>{option.label}</MenuItem>
)
))}
</Select>
</FormControl>
)
}
export default ExampleSelect;

Resources