I've currently got a modal set up, where once it's pressed, it opens a component of mine up. However, this component has a fixed css (which I want to keep), but when the modal is pressed, I want that CSS to change. Is this possible ? I've looked at a few things but can't seem to find something that works. What I've got currently can be seen below, and it doesn't override the original css.
const [currentModal, openModal] = useState(null);
const [appState, changeChange] = useState({
activeObject: null,
objects: [{id: 1}]
in the return
<div className="modal">
{currentModal === 'modal1' ?
<MyComponent>
</MyComponent>
: null}
<div class="class1">
{appState.objects.map((elements,index) => (
<button key={index} classnName="box active"
onClick={() => openModal('modal1')}>
<Modal1></Modal1>
</button>
))}
</div>
The CSS
.box{
width:200px;
height:200px;
margin:10px;
transition: background-color 0.1s ease-in-out;
}
.inactive{
background-color:pink;
}
.active {
background-color: blue;
width:200px;
height:200px;
margin:10px;
}
Use styled components: https://styled-components.com/docs/basics#adapting-based-on-props
Just pass a prop to the styled component wrapping your model. this prop will indicate if the modal has been pressed or not.
You'll have to change the css according to the prop value.
Related
I'm trying to create a catalogue which has a filter component. Once the filter button is clicked, it triggers a variable to turn true which then switches what is being shown on the screen. I want to know how I can make this switch smooth and ease in using css. Here is my code:
<div>
{this.state.showProjects === true &&
<div className="test">
{this.state.projects && this.state.projects.map((project) => (
<ProjectDetails key={project._id} project={project}/>
))}
</div>
}
{this.state.showProjects === false &&
<div className="initial-screen">
Enter filter options to get started!
</div>
}
</div>
Where and how should I incorporate the css ease property?
If I'm understanding what your ask is, you can implement a class-based solution that has your transition effects in there.
<div>
<div className=`test content ${this.state.showProjects && 'active'}`>
{this.state.projects && this.state.projects.map((project) => (
<ProjectDetails key={project._id} project={project}/>
))}
</div>
<div className=`initial-screen content ${!this.state.showProjects && 'active'}`>
Enter filter options to get started!
</div>
</div>
I added another class called content which would have the main transition styling that you would need for your animations. The active class would be your identifier as to what is currently being displayed.
.content {
opacity: 0;
transition-duraction: 2s;
transition-timing-function: ease;
&.active {
opacity: 100;
}
}
This would just add a simple fade-in/fade-out, but you can use this at a simple template for you to use to start adding in more styling; like movement.
I am using Next.js (React) with Bootstrap and styled JSX. I am running into an issue where a custom class in Bootstrap for a modal is only styled with css if the css if global. I declare the custom class using the dialogClassName property on the Modal. This is my function component (I am using Typescript):
const Form: React.FunctionComponent<props> = (props: props) => {
const [FormVisibility, FormDispatch] = useContext(FormContext);
return (
<Modal
show={props.isVisible}
onHide={() => {FormDispatch({ type: ActionTypes.CloseForm }) }}
backdrop="static"
dialogClassName="custom-modal"
>
<Modal.Header closeButton >
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={() => {FormDispatch({ type: ActionTypes.CloseForm }) }}>
Close
</Button>
</Modal.Footer>
<style jsx global>{`
.custom-modal {
color: blue;
height: 75vh;
width: 75vw;
max-width: none !important;
}
`}
</style>
</Modal>
);
}
This works just fine. But if I were to change <style jsx global> to <style jsx> then the styling isn't applied. Am I doing something wrong here or is there a better way to do this? It seems weird to me that global is needed even though the component has the class declared locally.
Thanks!
My experience working with Modals is that the modal element is actually extracted out of the DOM tree where your component lives and placed at the top most level right under the body tag.
<body>
// Component where the Modal is declared
<Form />
<div>
// Modal appears here
// Styles are not applied because Modal is not nested within Form component
</div>
</body>
It is possible that your local style is not applied because of this reason.
I'm trying to style a component in my React application, but I do not want to create an external stylesheet because it's a small project. How can I style this image component without using an external stylesheet?
return (
<div>
<Image>
<div>
<img src='./resources/image.png alt='image'>
</div>
</Image>
</div>
);
I've found resources online for using inline styling on a specific element, but I want to make my code clean by putting it at the top of the component like using a style tag at the top of an HTML file. I haven't been able to find anything that resembles this in React.
For inline styles you can define a style object, either at the top of the file, or in your render method, and then refer to it:
var myStyle = { margin: 10 }
return (
<div>
<Image>
<div>
<img style={myStyle} src='./resources/image.png alt='image'>
</div>
</Image>
</div>
)
More info in the docs: https://reactjs.org/docs/dom-elements.html#style
Internal CSS styling in JSX is very similar to how it's done in HTML. The only difference is that you need to declare the style names as variables because they are treated like JS objects. With this in mind, you also need to end each property with a comma instead of a semicolon, and the last property should have no punctuation at the end. Using this approach, you should also use style={} instead of className={}. You can read more about JSX styling here.
const myStyle = {
width: '300px',
height: '300px',
border: '2px solid black'
}
const Image = () => {
return (
<div>
<img style={myStyle} src='./resources/image.png alt='image'>
</div>
);
}
You can do something like this:
const Image = styled.div`
background: #1d9ac2;
img {
border: 1px solid red;
}
`;
There are several solutions for this, and a big debate about which one is "the best".
I don't know which one is the best, but I can tell you which one I use:
Styled components (https://www.styled-components.com/)
With this, you would define an object like this
let styled = require('styled-components');
// Or for fancy people
import styled from 'styled-components';
const Image = styled.div`
background-color: red;
/* You can even put classes or selectors in here that will match the sub-components */
.some_class_used_inside { color: black; }
img { width: 100px }
`
and use it like this
return (
<div>
<Image> {/* This will be the `<div>` with `background-color: red` */}
<div className="some_class_used_inside"> {/* This will now have `color: black` applied */
<img src='./resources/image.png alt='image'> {/* This will have `width: 100px` applied to it */}
</div>
</Image>
</div>
);
Ofcourse, there are many other libraries to do it, and everyone will have to find their own favorite I guess :)
I am having trouble getting my styled component to make a change to an <input /> wrapped in a React component. In Dev Tools I can see the style I am trying to override here:
.ui.input input {...}
I think the wrapping component needs to pass className to input i.e
<input className = {this.props.className} ..> ... </input>
but I cannot get the style to override with or without that. I will provide some snippets below.
//styled component
const StyledSearch = styled(Searchbar)`
&.ui.input input{
border: 0px !important;
}
`;
class SearchBar extends Component {
...
render() {
const style = {
display: this.state.showResults ? 'block' : 'none',
maxHeight: 500,
overflowY: 'scroll',
};
return (
<div className="ui search fluid" ref="container">
<div
className={`ui icon fluid input ${this.props.loading ? 'loading' : ''}`}>
<input type="text"
placeholder={this.props.placeholder}
onFocus={this.focus}
className = {this.props.className}
value={this.props.value}
onChange={this.props.onChange}/>
<i className="search icon"></i>
</div>
<div
className="results"
style={style}>
{
this.props.results.map((result, index) => (
<a
className="result"
key={index}
onClick={this.select.bind(this, result)}>
<div className="content">
{
result.get('image') ?
(
<div className="image">
<img src={result.get('image')} style={{ maxWidth: 50 }}/>
</div>
) : null
}
<div className="title">
{result.get('title')}
</div>
<div className="description">
{result.get('description')}
</div>
</div>
</a>
)
)
}
</div>
</div>
);}}
Basically, styled-components creates a new unique class name (in other words, a new namespace) for any DOM or React Components for which the styled function is called.
That means, when you use styled(SearchBar), styled-components wraps SearchBar component and attaches a unique class name to its root DOM. Then it passes that unique class name to the descendent DOMs and components (in your cases, nested div, input, a).
For this method to work, your root DOM must have a className that can be configured from outside. That's why, styled-components expects that, root DOM has the definition ${this.props.className} as the value of its className props. If your component lacks this, styled-components will not be able to create a new namespace which it can use to apply styling specific to it.
So, for your technique to work, you must assign ${this.props.className} as one of the values of className prop defined at the root div of SearchBar.
Working Demo
If you don't have access to SearchBar, you can wrap it with another component. Overhead of this process is that, you have to use an extra DOM level
Working Demo
From what I can tell, you need to apply the styles generated with styled-components to the wrapper element. This is due to the specificity of the .ui.input input external style. Meaning we can't simply target the input element with a new style because the .ui.input input selector is more specific and takes precedence. Here's a simple CSS example showing how the specificity of the .ui.input input selector takes precedence over the input styling:
.ui.input input {
border:2px solid red !important;
}
input {
border: 0px !important;
}
<div class="ui input">
<input />
</div>
This same issue is at play in your case. In the example below I've created a new Wrapper component, which has a style of:
&.ui.input input {
border: 0px !important;
font-size: 24px;
}
defined on it. This targets the inner input element, with more specificity, to override the external styles.
import React from 'react';
import ReactDOM from 'react-dom';
import styled from 'styled-components';
class InputWrapper extends React.Component {
render() {
const Wrapper = styled.div`
&.ui.input input {
border: 0px !important;
font-size: 24px;
}
`;
return(
<Wrapper className="ui input">
<input type="text" placeholder="Input" />
</Wrapper>
)
}
}
ReactDOM.render(
<InputWrapper />,
document.getElementById("app")
);
Here's a WebpackBin example.
Currently at version 4 you can do it as simple as
const Input = styled.input`
border:2px solid red !important;
`;
it will rendered as native input with SC className
I am working on the dynamic side bar for our project, basically what we want to do is to set up a dynamic side bar when user click on the side bar it will spread when user click back sidebar should collapse and show only icons (but not totally collapse it will keep the icons) for example before user click the icon. We are using sidenav.toggle()from angular material function which basically closes the sidebar completely and if I don't use toggle() function "Side" mode for navbar does not work. So I want collapse to icon with side mode. (The other reason we need to keep the side mode is that we also need to make sure when user spread the sidebar, right side content should push to right)
After user click the icon
Is there a way to do that?
Thanks.
Option 1: Generating Automatically:
You can create a navigation component from templates provided by Material itself using 'Angular CLI component schematics'
ng generate #angular/material:nav your-component-name
The above command will generate a new component that includes a toolbar with the app name and a responsive side nav based on Material breakpoints.
See more about angular material schematics here
Option 2: Implementing Manually:
To implement that, you just have to refer these two links:
Resizing Sidenav | Angular Material
Navigation List | Angular Material
glance through the following code. Implementation will be something like this:
<mat-drawer-container class="example-container mat-typography" autosize>
<mat-drawer #drawer mode="side" disableClose="true" opened="true">
<button mat-mini-fab (click)="isExpanded = !isExpanded" color="warn" style="margin: 10px;">
<mat-icon aria-label="Menu">menu</mat-icon>
</button>
<mat-nav-list>
<mat-list-item>
<mat-icon mat-list-icon>person</mat-icon>
<h4 mat-line *ngIf="isExpanded">Management A</h4>
</mat-list-item>
<mat-list-item>
<mat-icon mat-list-icon>assignment</mat-icon>
<h4 mat-line *ngIf="isExpanded">Management B</h4>
</mat-list-item>
<mat-list-item>
<mat-icon mat-list-icon>domain</mat-icon>
<h4 mat-line *ngIf="isExpanded">Management C</h4>
</mat-list-item>
<mat-list-item>
<mat-icon mat-list-icon>folder_shared</mat-icon>
<h4 mat-line *ngIf="isExpanded">Management X</h4>
</mat-list-item>
</mat-nav-list>
</mat-drawer>
<div class="example-sidenav-content">
You cards and screen Contents goes here..
Will be pushed towards right on expanding side navbar.
</div>
</mat-drawer-container>
I did this with a bit of CSS
mat-sidenav:not(.mat-drawer-opened) {
transform: translate3d(0, 0, 0) !important;
visibility: visible !important;
width: 60px !important;
overflow: hidden;
}
So when the draw is NOT open, the width of the sidenav is 60px and not 0. Just enough to show your icons.
OK, the next issue is that you'll need to hide a bunch of stuff like button name and other descriptive stuff, for me I need to change the height of the profile image and hide additional text. I did this in the same way as above using the :not selector:
mat-sidenav:not(.mat-drawer-opened) div.leftNav div.navProfile img {
width: 40px; margin: 16px 0 0px 0;
}
mat-sidenav:not(.mat-drawer-opened) .navTitle,
mat-sidenav:not(.mat-drawer-opened) .profileTitle {
display: none;
}
When collapsed I didn't want to show the button names so I wrapped the name in a *ngIf
<span class="navName" *ngIf="opened">{{ page?.name }} </span>
This should work, and it does but there is a problem. The ngIf is bound to the opened event and you will notice a delay when the event is firing (to account for it animation) to show your labels when the drawer is open.
To fix this I had to delve into the api of sidenav and found an eventemitter call openedStart and closedStart. I created a new bool in the component class,
showNavLabels: boolean;
then bound the events to this bool in the HTML.
<mat-sidenav class="sidenav" #sidenav mode="side" [(opened)]="opened"
(openedStart)='showNavLabels = !showNavLabels'
(closedStart)='showNavLabels = !showNavLabels' >
I am sure there is better way as I am not that experienced with Angular yet.
I hope it helps you out.
I created an example based on scss. Maybe someone can help to create the mobile version according to this sample.
Step 1: Add below style to styles.scss
// src/styles.scss
:root {
--menu-width-open: 200px;
--menu-width-closed: 64px;
}
.mat-drawer-container {
.mat-drawer {
box-sizing: content-box;
width: var(--menu-width-open);
transition: all 0.3s ease-in-out !important;
}
.mat-drawer-content {
// transform: translateX(200px);
margin-left: var(--menu-width-open) !important;
transition: all 0.3s ease-in-out !important;
}
&.container-closed {
.mat-drawer {
width: var(--menu-width-closed);
}
.mat-drawer-content {
// transform: translateX(64px) !important;
margin-left: var(--menu-width-closed) !important;
}
}
}
Step 2: Add drawer to app.componenet.html
<mat-drawer-container class="example-container" autosize [ngClass]="{ 'container-closed': !showFiller }">
<mat-drawer #drawer class="example-sidenav" mode="side" disableClose="true" opened="true">
<button (click)="showFiller = !showFiller" mat-raised-button>click</button>
</mat-drawer>
<div class="example-sidenav-content">
<router-outlet></router-outlet>
<button type="button" mat-button (click)="drawer.toggle()">Toggle sidenav</button>
</div>
</mat-drawer-container>
Step 3: And add showFiller = false; to app.component.ts file.
// app.component.ts
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
showFiller = false;
}
There is a feature request for this https://github.com/angular/material2/issues/1728
if you read the comments you'll also find a few examples on how to implement it yourself while it's not officialy available.