1. Creating Custom Styles using Props
To customize the style of a component based on props, move the column
definition outside of the component and create it as a function
that returns an array of objects. Then, in your JSX code, call this function while passing the necessary props or state.
2. Setting Custom Width
To set a custom width for a table column, use the tableLayout
property in the options object and set it to fixed
. Provide the desired width
for each column in the columns
array. Keep in mind that there is a known bug related to this feature, so monitor for updates. If your code breaks when the bug is fixed, refer to the issue resolution provided.
See Working Demo
Complete Code Snippet
const columns = propValue => [
{
title: "Avatar",
field: "avatar",
render: rowData => (
<img
style={{ height: 36, borderRadius: "50%" }}
src={rowData.avatar}
alt=""
/>
),
cellStyle: {
backgroundColor: "#039be5",
color: "#FFF"
},
width: "40%" //<---- set width here
},
{ title: "Id", field: "id" },
{ title: "First Name", field: "first_name" },
{
title: "Last Name",
field: "last_name",
cellStyle: {
backgroundColor: "#039be5",
color: "#FFF",
display: propValue ? "inline-block" : "block"
}
}
];
class App extends Component {
tableRef = React.createRef();
propValue = true;
render() {
return (
<div style={{ maxWidth: "100%" }}>
<MaterialTable
tableRef={this.tableRef}
columns={columns(this.propValue)}
data={query =>
new Promise((resolve, reject) => {
let url = "https://reqres.in/api/users?";
url += "per_page=" + query.pageSize;
url += "&page=" + (query.page + 1);
fetch(url)
.then(response => response.json())
.then(result => {
resolve({
data: result.data,
page: result.page - 1,
totalCount: result.total
});
});
})
}
title="Remote Data Example"
options={{ tableLayout: "fixed" }} // set table layout here
/>
<button
onClick={() => {
this.tableRef.current.onQueryChange();
}}
>
ok
</button>
</div>
);
}
}
NOTE: For material-table version 1.25 (or below), ensure to specify the column width inside the cellStyle
object:
cellStyle: {
backgroundColor: "#039be5",
color: "#FFF",
width: 10 //<----- define width like this
},